Python 如何检查jinja2模板中是否存在给定变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13956728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:00:30  来源:igfitidea点击:

How to check if given variable exist in jinja2 template?

pythonjinja2

提问by Rados?aw ?azarz

Let's say, I created a template object (f.e. using environment.from_string(template_path)). Is it possible to check whether given variable name exist in created template?

比方说,我创建了一个模板对象(fe using environment.from_string(template_path))。是否可以检查创建的模板中是否存在给定的变量名称?

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). How to check if variable x exist?

会产生任何影响(如果某些内容实际上是否会被“x 的文本”替换)。如何检查变量x是否存在?

采纳答案by jeffknupp

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,它将返回要评估的模板中使用的所有变量的列表。

回答by djc

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 以查看是否有引用,但这会有些复杂的代码。

回答by munk

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"

这将打印“未使用的变量”