Template Parser
Simple small and opinionated template parser without external dependencies (~950B minified).
Api
- parseTemplate - Replace tokens in text with provided values
- extractTokensFromTemplate - Get tokens metadata from provided template
parseTemplate
import { parseTemplate } from '@brandchamp/simple-template-parser';
const template = `
Hi {{FIRST-NAME}} {{LAST-NAME}},
Please register to our portal to earn free stuff
{{LINK-BUTTON "Register" REGISTER-URL}}
All the best
{{COMPANY-LOGO}}
`;
const { text, unreplacedTokens } = parseTemplate(template, {
'FIRST-NAME': 'John',
'LAST-NAME': 'Doe',
'COMPANY-LOGO': '<img src="http://company-logo.example.com"></img>',
'REGISTER-URL': 'https://register.example.com',
'LINK-BUTTON'(name, url) {
return `<a class="ui large primary button" href="${url}">${name}</a>`;
},
});
const { text, unreplacedTokens } = parseTemplate(template, {
'FIRST-NAME': 'John',
'COMPANY-LOGO': '<img src="http://company-logo.example.com"></img>',
});
import { extractTokensFromTemplate } from '@brandchamp/simple-template-parser';
const template = `
Hi {{FIRST-NAME}} {{LAST-NAME}},
Please register to our portal to earn free stuff
{{LINK-BUTTON "Register" REGISTER-URL}}
All the best
{{COMPANY-LOGO}}
P.S Keep in mind that token naming convention is up to you ;)
{{ functionName prop1 prop2 }}
`;
const tokens = extractTokensFromTemplate(template)
More examples
For more examples reference provided test test/templateParser.spec.ts