Friday, June 12, 2020

NodeJS Template Engine

Node file app.js

var nunjucks = require('nunjucks')

var res = nunjucks.render(
  'foo.html', {
    messages: ['foo', 'bar'],
    username: "mike"
  }
);

console.log(res)
template file foo.html
{% if username === 'mike' %}
    {{ username }}
{% endif %}

{% for message in messages %}
    {{ message }}
{% endfor %}
Run
node app.js
Practical example for oracle log message
var nunjucks = require('nunjucks')

var res = nunjucks.renderString(
  `
  '{{ "debug output " }}' || {% for var in variables %} '{{ var }} = ' || {{ var }} || {% endfor %}
`, {
    variables: ['foo', 'bar', 'baz']
  }
);

console.log(res.slice(0,-4))
Output
'debug output ' ||  'foo = ' || foo ||  'bar = ' || bar ||  'baz = ' || baz

No comments:

Post a Comment