I want to use Nunjucks templates but want to pass in my own JSON data to be used on the templates.
The documentation here is pretty sparse.
https://mozilla.github.io/nunjucks/templating.html
Thank you.
You can use gulp-data which allows you to pass json files to the task runner you're using to render Nunjucks.
gulp.task('nunjucks', function() {
return gulp.src('app/pages/**/*.+(html|nunjucks)')
// Adding data to Nunjucks
.pipe(data(function() {
return require('./app/data.json')
}))
.pipe(nunjucksRender({
path: ['app/templates']
}))
.pipe(gulp.dest('app'))
});
Found this gem here in 2019, but thought it'll be helpful for people like me, who have searched but didn't find anything.
First, create a template part with expected arguments in a macro
{% macro render(secTitle, secSubtitle) %}
<h4 class="heading">
{{ secTitle | safe }}, {{ secSubtitle | safe }}
</h4>
{% endmacro %}
Save it as [yourname].tpl
- in this case heading.tpl
Then, import this block and use a function specified in macro above (render()
in this case)
{% block heading %}
{% import "components/heading.tpl" as heading with context %}
{{ heading.render(
secTitle='Hello there',
secSubtitle='General Kenobi'
) }}
{% endblock %}
This will result in:
<h4 class="heading">
Hello there, General Kenobi
</h4>
Please notice | safe
after strings in a component - this means it'll output the string with HTML formatting (eg. <br>
will create a new line instead of outputting <br>
in text).
You can use their async render to achieve that.
https://mozilla.github.io/nunjucks/api.html#render
$.getJSON('/path/to/file.json', function (result) {
nunjucks.render('path/to/template/file.html', { result : result }, function (err, res) {
// do something
});
});
来源:https://stackoverflow.com/questions/31780560/how-can-i-pass-json-data-into-a-nunjucks-template