[英]How to check if given variable exist in jinja2 template?
Let's say, I created a template object (fe using environment.from_string(template_path)
). 假设我创建了一个模板对象(例如,使用environment.from_string(template_path)
)。 Is it possible to check whether given variable name exist in created template? 是否可以检查创建的模板中是否存在给定的变量名?
I would like to know, if 我想知道,如果
template.render(x="text for x")
would have any effect (if something would be actually replaced by "text for x" or not). 会产生任何效果(如果某项内容实际上被“ x的文本”所代替)。 How to check if variable x exist? 如何检查变量x是否存在?
From the documentation: 从文档中:
defined(value) 已定义(值)
Return true if the variable is defined: 如果定义了变量,则返回true:
{% if variable is defined %}
value of variable: {{ variable }}
{% else %}
variable is not defined
{% endif %}
See the default() filter for a simple way to set undefined variables.
EDIT: It seems you want to know if a value passed in to the rendering context. 编辑:似乎您想知道是否将值传递到渲染上下文中。 In that case you can use jinja2.meta.find_undeclared_variables , which will return you a list of all variables used in the templates to be evaluated. 在这种情况下,您可以使用jinja2.meta.find_undeclared_variables ,这将为您返回要评估的模板中使用的所有变量的列表。
I'm not sure if this is the best way, or if it will work in all cases, but I'll assume you have the template text in a string, either because you've created it with a string or your program has read the source template into a string. 我不确定这是否是最好的方法,还是在所有情况下都行得通,但是我假设您在字符串中包含模板文本,因为您已经使用字符串创建了模板或者您的程序已经读取将源模板转换为字符串。
I would use the regular expression library, re 我会使用正则表达式库
>>> import re
>>> template = "{% block body %} This is x.foo: {{ x.foo }} {% endblock %}"
>>> expr = "\{\{.*x.*\}\}"
>>> result = re.search(expr, template)
>>> try:
>>> print result.group(0)
>>> except IndexError:
>>> print "Variable not used"
The result will be: 结果将是:
'{{ x.foo }}'
or throw the exception I caught: 或抛出我捕获的异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: no such group
which will print "Variable not used" 它将显示“未使用变量”
You can't do that. 你不能那样做。
I suppose you could parse the template and then walk the AST to see if there are references, but that would be somewhat complicated code. 我想您可以解析模板,然后遍历AST以查看是否有引用,但这将是一些复杂的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.