I am trying to write some code which allows me to pass a doc as a string which is either plain txt or html and has some fields embeded i want to replace with personal values. something like for example like this
Hi {{ first_name | fallback: "there" }},
i will pass the field names as an object with same name so the lookup is easy. So what i am looking for coding ideas how to search for the {{ }} part and then check if field is not unknown, null or "" and if it is apply the fallback value in the tag. This is something like mailmerge but i dont want ths to be a docx file and output as word or pdf. i just want the processed string so i can pass back to my mail code and send message
Program that will do the following to achieve your output,
{{}}
|
trim()
fallback
valueReplace
the sting with desired valueHere is the example program that will do the above operation on step by step.
var str = 'Hi {{ first_name | fallback: "there" }},'
var data = {
first_name: "siva",
last_name: "sankar",
code: 29
}
function templateRender(str, data) {
return str.replace(/{{([^}]+)}}/g, function (match, string) {
var fallback = ''
var stringArr = string.split("|");
var value = stringArr[0].trim();
if (stringArr[1]) { fallback = stringArr[1].match(/(?<=fallback\:\s?)(["'].*?["'])/)[0].replace(/["']/g, "").trim(); }
return data[value] ? data[value] : fallback;
});
}
console.log("New String :::: ", templateRender(str, data));
Look at HandlebarsJs. It is exactly what Handlebars does, https://handlebarsjs.com
For your fallback you can use if.
{{#if first_name}}{{first_name}}{{else}}there{{/if}},
Which will default to there if first_name is falsey.
If you think if is a bit verbose you can write a helper function for defaults.
Handlebars.registerHelper('fallback', (val, def) => val || def);
and use it in a template
Hi {{fallback first_name 'there'}},
const template = Handlebars.compile(`Hi {{#if first_name}}{{first_name}}{{ else }}there{{/if}},`); console.log(template({ first_name: '' })); console.log(template({ first_name: 'Billy' })); Handlebars.registerHelper('fallback', (val, def) => val || def); const templateWithFallback = Handlebars.compile(`Hi {{fallback first_name 'there'}},`); console.log(templateWithFallback({ first_name: '' })); console.log(templateWithFallback({ first_name: 'Billy' }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.0/handlebars.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.