Action

Replace Placeholders

Posted by RosemaryOrchard, Last update over 3 years ago - Unlisted

This allows you to have a draft as a document template and replace «placeholders» with text of your choosing - creating a new draft.

Steps

  • script

    //This action is written as an arrow function (https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/) - it allows me to stop running code with "return" instead of stacking everything inside of "if, else" statements.
    (() => {
    	//collect «placeholders» as an object 
    	let placeholders = [];
    	let draftsContent = editor.getText();
    	let matches = draftsContent.match(/«(.+?)»/g);
    
    	for (match in matches) {
    		placeholders.push(matches[match]);
    	}
    
    	if (placeholders.length === 0) {
    		context.fail('No placeholders found');
    		return;
    	}
    	
    	var p = Prompt.create();
    	p.title = "Replace Placeholders";
    	p.message = "Here is a list of all the «placeholders» in this draft.";
    	
    	placeholders.forEach(function (placeholder) {
    		p.addTextField(placeholder, placeholder.replace("«", "").replace("»", ""), "");
    	});
    
    	p.addButton("Continue");
    	p.show();
    	
    	if (p.buttonPressed !== "Continue") {
    		context.cancel("Prompt was cancelled, user does not wish to continue;");
    		return;
    	}
    	
    	console.log(JSON.stringify(p.fieldValues));
    	
    	let newText = draftsContent;
    	placeholders.forEach(function (placeholder) {
    		console.log(placeholder);
    		console.log(p.fieldValues[placeholder]);
    		//replace any placeholder if they exist
    		newText = newText.replace(placeholder, p.fieldValues[placeholder]);
    	});
    	
    	//create a new draft and load it.
    	let d = Draft.create();
    	d.content = newText;
    	d.update();
    	editor.load(d);
    })();

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.