Action

New From Template

Posted by @mattgemmell, Last update almost 4 years ago

Create a new draft from a specified template. Supports [[cross-link]] backlinks. See the various configurable options at the top of the script. Requires Drafts 20.1 or later. Works well with my “Open Cross-Link at Cursor” action.

By Matt Gemmell — @mattgemmell — https://mattgemmell.com/

Steps

  • defineTemplateTag

    name
    newDraftTemplateName
    template
    Cross-Linked Draft Template
  • script

    /*
    
    Create new drafts via the same template system as my "Open Cross-Link at Cursor" action.
    
    Author: 		Matt Gemmell
    Twitter: 	@mattgemmell	https://twitter.com/mattgemmell
    Web: 			https://mattgemmell.com/
    
    */
    
    /* =========================== */
    // Configuration
    /* =========================== */
    
    
    var ensureInitialCapitals = true;
    /*
    If true, newly-created drafts will have their title's first letter made uppercase if necessary.
    */
    
    
    var newDraftTemplateName = "";
    /*
    Title of an existing draft which will be used as a template when creating new ones.
    If the template is not found, a blank draft will be created with the appropriate title.
    Use an empty string ("") to disable the template functionality.
    
    Notes:
    	- The new draft's title — i.e. the template's first non-blank line — will be replaced appropriately.
    	- Any leading hash/pound symbols (i.e. "#") will be preserved when setting the new title.
    	- Drafts template tags will be processed (https://docs.getdrafts.com/docs/actions/templates ).
    	- Some custom template tags are available:
    	
    		- source_display_title is the display title of the source draft which created the new draft.
    		- source_uuid is the UUID of the source draft which created the new draft.
    		- source_title_link is a preformatted [[backlink]] to the source draft's display title.
    		- source_uuid_link is a preformatted [[u:backlink]] to the source draft's UUID.
    */
    
    
    var inheritTagsFromTemplate = true;
    /*
    If true, any tags which are applied to the template will also be applied to each new draft created from it.
    */
    
    
    var excludedTags = ["template"];
    /*
    The tags present in this array will NOT be inherited by new drafts created from the template. Has no effect if inheritTagsFromTemplate (above) is false.
    */
    
    
    var prependToNewTitles = "";
    /*
    A string to prepend to the titles of new pages (but after any leading Markdown headers and whitespace from the template). This string will be processed for Drafts template tags first, in the contetx of the new draft. A useful example for unique identifiers would be: "[[date|%Y%m%d%H%M%S]] "
    */
    
    
    /* =========================== */
    // END of Configuration
    /* =========================== */
    
    
    /* =========================== */
    // A few useful functions.
    /* =========================== */
    
    
    function getTitle(theDraft) {
    	return theDraft.displayTitle;
    }
    
    function openDraft(theDraft) {
    	editor.load(theDraft);
    	editor.activate();
    }
    
    
    /* =========================== */
    // End of functions.
    /* =========================== */
    
    
    // Default to suggesting the selected text as a title.
    var createDraft = true;
    var draftTitle = "";
    if (draft) {
    	var selText = editor.getSelectedText();
    	if (selText && selText.length > 0) {
    		draftTitle = selText;
    	}
    }
    
    // Ask for title of the new draft.
    var prompt = Prompt.create();
    prompt.isCancellable = true;
    prompt.title = "Title of new draft?";
    prompt.addTextField("titleField", "", draftTitle, {"wantsFocus": true});
    prompt.addButton("Create");
    createDraft = prompt.show();
    
    if (createDraft) {
    	var titleFieldContents = prompt.fieldValues["titleField"].trim();
    	if (titleFieldContents && titleFieldContents.length > 0) {
    		draftTitle = titleFieldContents;
    	} else {
    		createDraft = false;
    	}
    }
    
    if (createDraft) {
    	var newDraft = new Draft();
    
    	// Deal with initial capitals.
    	if (ensureInitialCapitals) {
    		draftTitle = draftTitle.charAt(0).toUpperCase() + draftTitle.slice(1);
    	}
    	
    	// Deal with prepended title string, if set.
    	if (prependToNewTitles.length > 0) {
    		draftTitle = newDraft.processTemplate(prependToNewTitles) + draftTitle;
    	}
    
    	newDraft.content = "# " + draftTitle + "\n\n";
    	
    	// Handle template requirements.
    	if (newDraftTemplateName == null || newDraftTemplateName == "") {
    		newDraftTemplateName = draft.getTemplateTag("newDraftTemplateName");
    	}
    	
    	if (newDraftTemplateName != null && newDraftTemplateName != "") {
    		// Attempt to locate template.
    		var foundTemplates = Draft.queryByTitle(newDraftTemplateName);
    		if (foundTemplates.length > 0) {
    			var template = foundTemplates[0];
    			var templateContent = template.content;
    			
    			// Replace title appropriately.
    			templateContent = templateContent.replace(template.displayTitle, draftTitle);
    			
    			// Process template tags.
    			newDraft.setTemplateTag("source_display_title", draft.displayTitle);
    			newDraft.setTemplateTag("source_uuid", draft.uuid);
    			newDraft.setTemplateTag("source_title_link", "\[[" + draft.displayTitle + "]]");
    			newDraft.setTemplateTag("source_uuid_link", "\[[u:" + draft.uuid + "]]");
    			templateContent = newDraft.processTemplate(templateContent);
    			
    			// Transfer tags if appropriate.
    			if (inheritTagsFromTemplate) {
    				for (tag of template.tags) {
    					if (!excludedTags.includes(tag)) {
    						newDraft.addTag(tag);
    					}
    				}
    			}
    			
    			// Apply contents to our new draft.
    			newDraft.content = templateContent;
    			
    		} else {
    			app.displayInfoMessage("Couldn't find new draft template.");
    		}
    	}
    	
    	// Open draft.			
    	if (newDraft != null) {
    		newDraft.update();
    		openDraft(newDraft);
    	}
    }
    

Options

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