How can I pass JSON data into a Nunjucks template?

此生再无相见时 提交于 2020-01-02 01:16:18

问题


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.


回答1:


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'))
});



回答2:


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).




回答3:


Simply use dump and safe filters combined:

<script>
  const choices = {{ yourJsonVar | dump | safe }};
</script>



回答4:


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

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