学习Nunjucks (Jinja2)如何正确地将JSON数据传递给视图?

时间:2021-11-20 20:46:39

I'm learning how to nunjucks and I understand how to use templates but cannot properly figure out how to insert data from json objects.

我正在学习如何nunjucks,我也知道如何使用模板,但是我不能正确地理解如何从json对象插入数据。

Here is my attempt I was able to hard code it into the template itself as a variable. But how can I source it from an external source out side of the template?

这是我的尝试,我能够硬编码它到模板本身作为一个变量。但是,我如何从模板外部的一个外部源获取它呢?

学习Nunjucks (Jinja2)如何正确地将JSON数据传递给视图?

2 个解决方案

#1


1  

Pass the required parameters when calling Nunjucks.render, like this:

调用Nunjucks时传递所需的参数。渲染,像这样:

nunjucks.render("items.html", { items: [ ... ] });

items will be available on top of the default foo variable set globally. In the template (items.html) you can simply access items like you do now (just remove the declaration of items from the .html.

项目将在全局的默认foo变量集之上可用。在模板(items.html)中,您可以像现在这样简单地访问项目(只需从.html中删除项的声明)。

#2


0  

nunjucks escapes html by default you have to tell it explicitly that you input is "safe" using the safe filter. Let say your JSON string is in myData and you wanted to use it as a javascript variable myVar you would write in your template:

nunjucks转义html默认情况下,您必须明确地告诉它您的输入是“安全的”,使用安全过滤器。假设你的JSON字符串在myData中,你想用它作为javascript变量myVar你要在模板中写:

var myVar = {{ myData | safe }};

#1


1  

Pass the required parameters when calling Nunjucks.render, like this:

调用Nunjucks时传递所需的参数。渲染,像这样:

nunjucks.render("items.html", { items: [ ... ] });

items will be available on top of the default foo variable set globally. In the template (items.html) you can simply access items like you do now (just remove the declaration of items from the .html.

项目将在全局的默认foo变量集之上可用。在模板(items.html)中,您可以像现在这样简单地访问项目(只需从.html中删除项的声明)。

#2


0  

nunjucks escapes html by default you have to tell it explicitly that you input is "safe" using the safe filter. Let say your JSON string is in myData and you wanted to use it as a javascript variable myVar you would write in your template:

nunjucks转义html默认情况下,您必须明确地告诉它您的输入是“安全的”,使用安全过滤器。假设你的JSON字符串在myData中,你想用它作为javascript变量myVar你要在模板中写:

var myVar = {{ myData | safe }};