How can I pass JSON data into a Nunjucks template?

故事扮演 提交于 2019-12-05 01:29:47
yahyazini

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
        });
    });
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!