A server-side javascript template library like nunjucks.
npm install node-mus
const Mus = require('node-mus');
const mus = new Mus();
mus.renderString('{{ mus }}', { mus: 'hello mus' }); // hello mus;
or you can see the test example
- variable
- comment
- for
- if else
- set
- raw
- macro
- filter
- extends
- block
- include
- blockStart
default: {%
- blockEnd
default: %}
- variableStart
default: {{
- variableEnd
default: }}
- noCache
default: false
const mus = new Mus({
blockStart: '<%',
blockEnd: '%>',
variableStart: '<%=',
variableEnd: '%>'
});
const template = '<% if test %><div><%= test %></div><% endif %>';
mus.renderString(template, { test: '123' });
// '<div>123</div>'
render template file to html
render template string to html
create self-defined filter
mus.renderString('{{ obj.hello }}{{ obj.mus }}', {
obj: {
hello: 'hello',
mus: 'mus'
}
}); // hello mus;
mus.renderString('{{ test > 0 ? text : "nothing" }}', {
test: 1,
text: 'hello mus',
}); // hello mus;
mus.renderString('{{ text | nl2br | safe }}', {
text: 'hello \n mus',
}); // hello <br/> mus;
mus.renderString('11{# {{ test }} #}', {
test: 'hello mus',
}); // 11;
mus.renderString('{% for item in list %}({{ loop.index0 }}:{{ item }}){% endfor %}', {
list: [1, 2],
}); // (0:1)(1:2)
mus.renderString('{% if test > 1 %}{{ test }}{% endif %}', {
test: 2
}); // 2
const tpl = '{% if test > 2 %}{{ test }}{% elseif test === 2 %}111{% else %}333{% endif %}';
mus.renderString(tpl, {
test: 2
}); // 111
mus.renderString('{% set test = test2 %}{{ test }}', {
test2: 2,
}); // 2
mus.renderString('{% raw %}{{ test }}{% endraw %}', {
test: 2
}); // {{ test }}
mus.renderString('{% macro test %}123{% endmacro %}{{ test() }}'); // 123
template 1: test.tpl
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
{% block main %}
test.tpl content
{% endblock %}
</body>
</html>
template 2: test2.tpl
{% extends './test.tpl' %}
{% block main %}
test2.tpl content
{% endblock %}
render
mus.render('test2.tpl');
// <!doctype html> ... test2.tpl content ...
template 1: test.tpl
{% include './test2.tpl' %}
template 2: test2.tpl
hello mus
render:
mus.render('test.tpl');
// hello mus
npm test
npm run cov
MIT