1.摘要
我找不到,像if any() in object
/if all() in object
这样的表达式在JJIA2中的正确语法是什么.
2.MCVE
-
"""Jinja2 if any() in object MCVE.""" from jinja2 import Template KIRA_BLOCK = """ {% if 14 in range(1,5) or 4 in range(1,5) or 7 in range(1,5) %} Kira Goddess! {% endif %} """ print(Template(KIRA_BLOCK).render())
如何才能在没有重复代码的情况下获得相同的结果?
3.无能为力
-
我试着在谷歌、GitHub和Jinja documentation上搜索我的问题的答案和类似的例子
-
我不知道怎么用Jinja built-in filters来解决我的问题
-
我试了
select()
滤镜,就像this answer on Stack Overflow中推荐的那样.就像这样:KIRA_BLOCK = """ {% if (14,4,7)|select|first in range(1,5) %} Kira Goddess! {% endif %} """
-
我try 注册一个自定义的
any()
过滤器,就像在Stack Overflow上的同一个答案中所建议的那样.就像这样:"""Jinja2 if any() in object MCVE.""" from jinja2 import Environment from jinja2 import Template environment = Environment() environment.filters["any"] = any KIRA_BLOCK = """ {% if (14,4,7)|any in range(1,5) %} Kira Goddess! {% endif %} """ print(Template(KIRA_BLOCK).render())
4.真实例子
预防XY problem:
我在静态站点生成器Pelican中使用类似的模板.示例:
{# [INFO] If any of the classes "attention", "caution" or "warning" exists in my article, I add specific styles #}
{% if "class=\"attenion\"" in article.content or if "class=\"caution\"" in article.content or if "class=\"warning\"" in article.content %}
<link rel="preload" href="path/to/css/third-party/Admonition/admonition-warning.min.css" as="style" onload="this.rel='stylesheet'">
{# [INFO] Elif all classes "faq", "help" and "question" exists in my article, I add another styles #}
{% elif "class=\"faq\"" in article.content and if "class=\"help\"" in article.content and if "class=\"question\"" in article.content %}
<link rel="preload" href="path/to/css/third-party/Admonition/admonition-question.min.css" as="style" onload="this.rel='stylesheet'">
{% endif %}
我不明白如何从这些模板中删除硬编码.
谢谢.