Skip to content

Instantly share code, notes, and snippets.

@plugn
Forked from niccai/lodash-node-templateSettings
Last active April 16, 2021 20:32
Show Gist options
  • Save plugn/406d122ab411ea5cb2470704811c46f3 to your computer and use it in GitHub Desktop.
Save plugn/406d122ab411ea5cb2470704811c46f3 to your computer and use it in GitHub Desktop.
Changing lodash/underscore template settings in Node.js to use Mustache style braces
// Client side, you typically see the template style changed to {{ }} like so...
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/gim,
evaluate: /\{\#(.+?)\#\}/gim
};
/*
However, in Node.js, this causes issues when trying to render a template.
Likely, you haven't paid too much attention to the fact that you are setting
_.templateSettings outright above. Thus, losing other settings like escape and variable.
AND FOR NODE.JS, IMPORTS IS ALSO LOST.
*/
// Therefore, you should set only what you need to explicitly.
_.templateSettings.interpolate = /\{\{(.+?)\}\}/gim;
_.templateSettings.evaluate = /\{\#(.+?)\#\}/gim;
var s = `{"code":"ERR_CONTRAGENT_UNREMOVABLE","message":"Contargent {{ id }} can not be removed because it {{ reason }}","args":{"sys_id":210842,"name":"Закиров Радик Сарварович","reason":"has_docs_or_catalog","id":"84dda3f1-d113-4648-91a4-46576469eec3"},"why":[]}`
var tplConf = {
interpolate : /\{\{(.+?)\}\}/gim,
evaluate: /\{\#(.+?)\#\}/gim
}
var o = JSON.parse(s)
var t = _.template(o.message, tplConf)
var r = t({id: '', user: 'USER', reason: 'REASON'})
console.log('o:', o)
console.log('t:', t)
console.log('r: ', r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment