Joh*_*ier 34 python code-generation jinja2
我在Jinja2中进行代码生成,我经常想要一起遍历两个列表(即变量名称和类型),是否有一种简单的方法可以执行此操作,还是只需要传递一个预压缩列表?我无法在文档或谷歌搜索中找到这样的功能.
Gar*_*ett 40
如果您认为合适,请修改jinja2.Environment 全局命名空间.
import jinja2
env = jinja2.Environment()
env.globals.update(zip=zip)
# use env to load template(s)
Run Code Online (Sandbox Code Playgroud)
这可能有助于将视图(模板)逻辑与应用程序逻辑分离,但它也可以反转.#separationofconcerns
对于 Flask,您可以将 zip 传递到render_template()
return render_template("home.html", zip=zip)
Run Code Online (Sandbox Code Playgroud)
既然您没有提到是否使用Flask,我想我会添加我的发现。
通过所使用render_template()创建使用的“拉链”过滤器zip()中通过瓶使用的环境的Jinja2功能。
app = Flask(__name__)
...
app.jinja_env.filters['zip'] = zip
Run Code Online (Sandbox Code Playgroud)
要在模板中使用此代码,请按照以下步骤操作:
{% for value1, value2 in iterable1|zip(iterable2) %}
{{ value1 }} is paired with {{ value2 }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
请记住,字符串是可迭代的Jinja2,因此,如果尝试压缩到字符串,则会得到一些疯狂的东西。为了确保要压缩的内容是可迭代的,而不是字符串,请执行以下操作:
{% if iterable1 is iterable and iterable1 is not string
and iterable2 is iterable and iterable2 is not string %}
{% for value1, value2 in iterable1|zip(iterable2) %}
{{ value1 }} is paired with {{ value2 }}
{% endfor %}
{% else %}
{{ iterable1 }} is paired with {{ iterable2 }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10632 次 |
| 最近记录: |