【问题标题】:How can I pass JSON data into a Nunjucks template?如何将 JSON 数据传递到 Nunjucks 模板?
【发布时间】:2015-08-03 06:18:42
【问题描述】:

我想使用 Nunjucks 模板,但想传入我自己的 JSON 数据以用于模板。

这里的文档很少。

https://mozilla.github.io/nunjucks/templating.html

谢谢。

【问题讨论】:

标签: jinja2 nunjucks


【解决方案1】:

您可以使用gulp-data 它允许您将 json 文件传递​​给用于渲染 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'))
});

【讨论】:

  • 你知道是否有与 gulp-data 相关的 webpack 吗?我想用 Webpack 将 data.json 传递给 nunjucks。
【解决方案2】:

只需结合使用dumpsafe 过滤器:

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

【讨论】:

    【解决方案3】:

    2019 年在这里找到了这颗宝石,但认为它对像我这样搜索过但没有找到任何东西的人会有所帮助。

    首先,在宏中创建一个带有预期参数的模板部分

    {% macro render(secTitle, secSubtitle) %}
        <h4 class="heading">
            {{ secTitle | safe }}, {{ secSubtitle | safe }}
        </h4>
    {% endmacro %}
    

    另存为[yourname].tpl - 在本例中为heading.tpl

    然后,导入此块并使用上面宏中指定的函数(本例中为render()

    {% block heading %}
        {% import "components/heading.tpl" as heading with context %}
        {{ heading.render(
            secTitle='Hello there',
            secSubtitle='General Kenobi'
        ) }}
    {% endblock %}
    

    这将导致:

    <h4 class="heading">
        Hello there, General Kenobi
    </h4>
    

    请注意组件中字符串后面的| safe - 这意味着它将以 HTML 格式输出字符串(例如,&lt;br&gt; 将创建一个新行,而不是在文本中输出 &lt;br&gt;)。

    【讨论】:

    • 您在这个示例中唯一缺少的是如何将来自 somefile.js 的 json 数据关联到您的模板宏。我认为你会在揭露这一点时得到更多的支持。
    【解决方案4】:

    您可以使用他们的异步渲染来实现这一点。

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

    【讨论】:

    • 这似乎只是为我打印[object Object]
    • 那是因为你得到了一个包含其中对象的数组。您需要将 result : result 扩展为 JSON 的构造方式,如 result : result[0] 或传递函数参数中的第一个数组项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2018-08-19
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多