在jinja2的几个地方重新使用一段代码 [英] Reuse a block of code in several places in jinja2
问题描述
< div class 我有这个html片段,需要在jinja2模板的很多地方使用。 =usedalot> {{somevalue}}< / div>
例如在template1.html,template2.html中。 template3.html,这个代码重复了几个地方
<! - template1.html,template2.html。 template3.html - >
< div class =usedalot> {{somevalue}}< / div>
......
< div class =usedalot> {{somevalue}}< / div>
....
< div class =usedalot> {{somevalue}}< / div>
......
不用复制和粘贴,有没有办法使用这段代码片段作为一个块? jinja2模板继承(与块)似乎并没有解决这个问题。
你正在寻找什么叫做<一个href =http://jinja.pocoo.org/docs/templates/#macros =noreferrer>宏。
宏放在单独的文件中(例如 macros.html
)。
{%macro usedalot(somevalue)%}
< div class =usedalot> {{somevalue}}< / div>
{%endmacro%}
然后,您可以将宏导入其他模板
{%from'macros.html'import usedalot%}
然后在需要时使用它们
$ b $ pre $ {{usedalot(1)}}
这将输出
< div class =usedalot> 1< / div>
I have this html snippet which needs to be used in lots of places in the jinja2 templates:
<div class="usedalot">{{ somevalue }}</div>
for example, in template1.html, template2.html. template3.html, this code is repeated several places
<!-- template1.html, template2.html. template3.html -->
<div class="usedalot">{{ somevalue }}</div>
......
<div class="usedalot">{{ somevalue }}</div>
....
<div class="usedalot">{{ somevalue }}</div>
......
Instead of copying and pasting, is there someway to use this code snippet as a block? The jinja2 template inheritance (with blocks) do not seem to solve this problem.
What you are looking for is called a macro.
Macros are placed in separate files (e.g., macros.html
).
{% macro usedalot(somevalue) %}
<div class="usedalot">{{ somevalue }}</div>
{% endmacro %}
You can then import your macros in other templates
{% from 'macros.html' import usedalot %}
and then use them whenever needed
{{ usedalot(1) }}
This will output
<div class="usedalot">1</div>
这篇关于在jinja2的几个地方重新使用一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!