Action

Craft Document From Template

Posted by FlohGro, Last update almost 3 years ago

UPDATES

almost 3 years ago

typo fixed

show all updates...

almost 3 years ago

typo fixed

almost 3 years ago

updated documentation

almost 3 years ago

description update

about 3 years ago

updated description for existing templates in Craft

created by @FlohGro / more on my Blog

Craft Document From Template

This action creates documents in Craft from templates stored in Drafts.

You can setup as many templates as you want. They are identified from the action by one or more configurable tags you apply to the template drafts. The action also supports you to easily create new templates with your configured tags.

The action will query for all drafts with the configured tag(s) (its optionally possible to configure tags which shall be omitted). A prompt will be displayed where you can select the template you want to use.

After selecting a template the action will create and open the new document in Craft.

[Configuration]

Before you can use the action you have to configure it to your needs as follows.

  • template tags: you have to configure the tags which your templates should include (the action will only display these drafts in the menu)
    • therefore you have to edit the script step of the action
    • in line 4 const templateTags = ["3 template", "3 sw craft"]; you will see the constant „templateTags“
      • this constant defines the tags which identify your craft template drafts. Please add them as comma-separated-strings into the array.
      • feel free to delete the standard configuration of "3 template", "3 sw craft"
      • make sure to at at least one tag into the array
  • [optional] template omit tags: you can configure tags which should not be included in the drafts found by this action
    • e.g. you have configured your templateTags to “3 template”, “3 sw craft“, but you have other drafts with the tag „todo“ which should be ignored by this action
    • add these tags into the empty array of the constant „templateOmitTags“ in line 7 const templateOmitTags = []; and the corresponding drafts containing this tag will be ignored by this action

When you first run any of my Craft actions requiring the space id it will ask you to store the space id of your Craft space. This is a one time action and you don’t need to do it for any other of my Craft actions you install.

To retrieve your spaceId just copy the deeplink of any document in that space (refer to the Craft Support Page when you don’t know how to do that). Paste the copied id into a draft and you will se a link similar to this: "craftdocs://open?blockId=[the block id]&spaceId=[the spaceId]” - find the character combination “[the spaceId]” after the “spaceId=” and copy it and paste it into the prompt of this action.

If you don’t wan’t to use the (any of my) action for different Craft spaces there is no further configuration needed.

To use these actions with different spaces you need to duplicate the action for each space you want to use it. I recommend to e.g. add a suffix to the action name to describe the space for which you configure it.

The action uses Drafts possibility to store credentials to distinguish different spaces. When you duplicate the action for another space you have to change the name of the credential. Therefore you need edit this line const spaceIdCredentialName = "CraftDocumentSpace" in the script step of the action and change the CraftDocumentSpace to something different (e.g. describe the space in a suffix like „CraftDocumentSpacePersonal" or „CraftDocumentSpaceWork“. If you use several of my Craft actions you should use the same credential name in all of them.

[Usage]

Setting up templates

When you finished the [Configuration] you can start setting up your templates. If you already have drafts with the configured tags they will directly show up in the prompt of the action.

If you don’t have any draft with the configured tag(s), the prompt will just display a button “[Create New Template]” when you select that button, Drafts will create a new Draft with the configured tags and a default content.

Replace the title with the name of your template (which will be the title of the created Craft Document) and just insert the content you want to have in that template in markdown format

Setup as many templates as you want

Creating Documents from Templates

When you configured the action and set up one or more templates the action can be used very easily.

When you run it the prompt will display the titles of all drafts with the configured tags, just select the template you want to use and the action will create and directly open the new document in Craft.


If you find this useful and want to support me you can

Buy Me A Coffee

Steps

  • script

    // craft create note from template - created by @FlohGro
    
    // this constant defines the tags which identify your craft template drafts. Please add them as comma-separated-springs into the array to let the action find the correcht drafts
    const templateTags = ["3 template", "3 sw craft"];
    
    // this constant can be configured optionally. If you have drafts with the same tags in the templateTags array which should not be used as template in this action, please add the extra tags which identify the drafts which shouldn't be used as templates here
    const templateOmitTags = [];
    
    // ----------------------------------------------------------------
    // END OF CONFIGURATION - CHANGING ANYTHING BELOW WILL PROBABLY BREAK THE FUNCTIONALITY OF THE ACTION
    // ----------------------------------------------------------------
    
    const spaceId = getCraftSpaceIdToUse();
    
    if (spaceId) {
        let templateDrafts = Draft.query("", "all", templateTags, templateOmitTags, "accessed", false, false)
    
        let selectedDraft = selectTemplateDraftFromPrompt(templateDrafts);
    
        if (selectedDraft) {
    
            let createdDocumentBlockId = createCraftNoteFromDraft(selectedDraft);
    
            if (createdDocumentBlockId) {
                let blockId = createdDocumentBlockId;
                openCraftDocumentWithBlockId(blockId)
            }
    
        }
    
    } else {
        // error notification already fires in function
    }
    
    // -----------------------------------------------------------------
    // function definitions
    // -----------------------------------------------------------------
    
    function getCraftSpaceIdToUse() {
        let credential = Credential.create("CraftDocumentSpace", "Credential to store the spaceId of the space you want to use in Drafts.\ninsert your spaceId into the TextField below. \n\nNOTES: \n- this is a one time action, you don't need to do it everytime\n- Multiple spaces are currently not supported with this spaceId credential helper");
        credential.addTextField("spaceId", "spaceId");
        if (credential.authorize()) {
            return credential.getValue("spaceId");
        } else {
            let errorStr = "failed storing / retrieving space Id with credential"
            app.displayErrorMessage(errorStr);
            context.fail(errorStr);
            console.log(errorStr);
            return false;
        }
    }
    
    
    
    function selectTemplateDraftFromPrompt(templateDrafts) {
    
        let p = Prompt.create();
        p.title = "select template";
    
        p.addButton("[Create New Template]");
        for (templateDraft of templateDrafts) {
            p.addButton(templateDraft.displayTitle, templateDraft)
        }
    
        if (p.show()) {
            if (p.buttonPressed != "[Create New Template]") {
                return p.buttonPressed;
            } else {
                let newTemplateDraft = new Draft()
                for (tag of templateTags) {
                    newTemplateDraft.addTag(tag);
                }
                newTemplateDraft.content = "# New Template Draft\n"
                newTemplateDraft.update();
                alert("created new template draft and will load it now.")
                editor.load(newTemplateDraft);
                return false;
    
            }
        } else {
            context.cancel();
            return false;
        }
    
    
    }
    
    function createCraftNoteFromDraft(inputDraft) {
    
    
        let title = inputDraft.displayTitle
    
        let content = inputDraft.processTemplate("[[body]]")
    
        content = encodeURIComponent(content)
    
        const baseURL = "craftdocs://x-callback-url/createdocument?"
    
        let cbCreate = CallbackURL.create()
        cbCreate.baseURL = baseURL
        cbCreate.addParameter("spaceId", spaceId)
        cbCreate.addParameter("title", title)
        cbCreate.addParameter("content", content)
        cbCreate.addParameter("folderId", "")
        cbCreate.waitForResponse = true
    
        let result = cbCreate.open()
    
        if (result == true) {
            console.log("Craft note successfully created")
            // parse result:
            let craftCreateResult = cbCreate.callbackResponse
            var blockId = craftCreateResult.blockId
    
            return blockId;
        } else {
            console.log("Craft note result:" + cb.status + " " + cb.callbackResponse)
            if (cb.status == "cancelled") {
                context.cancel()
            } else {
                context.fail()
            }
            return false;
        }
    
    }
    
    
    function openCraftDocumentWithBlockId(blockId) {
        const baseURL = "craftdocs://open?"
        let cbOpen = CallbackURL.create()
        cbOpen.baseURL = baseURL
        cbOpen.addParameter("spaceId", spaceId)
        cbOpen.addParameter("blockId", blockId)
        cbOpen.waitForResponse = false;
        cbOpen.open();
    }

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.