将变量传递到 jinja 导入或包含父 html 文件
场景是:
“你有一个名为 person 的变量,其中包含许多字段,如姓名、地址等,你想将其传递给部分 html” - 该解决方案可能是搜索客户的结果,例如
代码片段.html
<div id="item">
<ul>
<li>
<span>{{name}}</span>
<span>{{address}}</span>
<li>
</ul>
</div>
mypage.html
<div id="result">
{% include "snippet.html" passing {{person}} %}
</div>
实现此目的的最佳方法是什么。在文档中,它讨论了在各处传递上下文,但在我看来,渲染模板时这似乎是一个相当大的对象。将特定对象传递到每个模板中肯定更容易吗?
The scenario would be:
"you have a variable called person which contains a number of fields like name, address, etc which you want to pass to a partial piece of html" - this solution could be results from a search for customers for example
snippet.html
<div id="item">
<ul>
<li>
<span>{{name}}</span>
<span>{{address}}</span>
<li>
</ul>
</div>
mypage.html
<div id="result">
{% include "snippet.html" passing {{person}} %}
</div>
What is the best way to achieve this. In the documentation it talks about passing context around everywhere, but that seems to me to be a rather large object when rendering templates. surely it is easier to pass specific objects into each template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将一个模板包含到另一个模板中时,它可以访问其上下文,因此如果您将
person
变量传递给mypage.html
的上下文,您将能够从导入的模板访问它,如下所示:snippet.html:
mypage.html:
view.py:
When you include a template into another one, it gains access to its context, so if you pass your
person
variable tomypage.html
's context, you'll be able to access it from your imported template like this:snippet.html:
mypage.html:
view.py:
这补充了这个答案,作者是 mdeous.
环境全局变量在宏中始终可用,但上下文变量则不然。
要在导入的宏中使用上下文,您必须在导入时使用with context,例如:
This complements this answer by mdeous.
Environment globals are always available in macros, but context variables are not.
To have the context available in an imported macro, you have to use with context when importing, e.g.: