仅使用上下文作为参数调用 jinja2 过滤器
Calling a jinja2 filter with only the context as an argument
我正在尝试在我的服务中呈现一个 jinja2 模板(不使用烧瓶,只是纯 jinja2 并构建一个 jinja2 环境。
假设我定义了以下过滤器
import jinja2
@jinja2.contextfilter
def my_function(context):
if context.get('my_var'):
return "hello"
else:
return "world"
超级简化的例子,但重点是我有一些逻辑有条件地 returns 一个基于某些传递到上下文的变量的值。
此外,我正在使用 jinja2 2.11 或类似的东西,这就是为什么我使用 @contextfilter
而不是 @pass_context
。
我已使用 env.filters['my_function'] = my_function
将此过滤器添加到我的环境中
在渲染模板时,我调用
template = env.get_template('my_template.html')
template.render({'my_var': 'some_value'})
模板可能类似于
... some html here
{{ my_function }}
... some more html
这实际上并不是 return“你好”,而只是 empty/blank。
我通过传入一个虚拟变量设法得到它
@jinja2.contextfilter
def my_function(context, value):
.... code is the same
然后在模板中,我用 {{ 'hi' | my_function }}
调用它。但显然这只是一种 hack,并不是很理想。
所以我的问题是,如何调用仅将上下文作为参数的 jinja2 过滤器函数?我试过 {{ my_function() }}
return 错误 UndefinedError: 'my_function' is undefined
和 {{ | my_function }}, which returns the error
TemplateSyntaxError: unexpected '|'`
或者我应该使用其他一些 jinja2 构造?
编辑:我怀疑 jinja2 使用 |
来识别过滤器和变量,因为我没有 |
,所以它试图只渲染变量 my_function
来自上下文,因为它不存在于上下文中,所以它只输出一个空字符串。
Jinja2 调用这些函数 global functions(如 range()
),而不是过滤器。只需在这一行中将 filters
更改为 globals
:
env.globals['my_function'] = my_function
然后您可以在模板中调用您的函数:{{ my_function() }}
。
我正在尝试在我的服务中呈现一个 jinja2 模板(不使用烧瓶,只是纯 jinja2 并构建一个 jinja2 环境。
假设我定义了以下过滤器
import jinja2
@jinja2.contextfilter
def my_function(context):
if context.get('my_var'):
return "hello"
else:
return "world"
超级简化的例子,但重点是我有一些逻辑有条件地 returns 一个基于某些传递到上下文的变量的值。
此外,我正在使用 jinja2 2.11 或类似的东西,这就是为什么我使用 @contextfilter
而不是 @pass_context
。
我已使用 env.filters['my_function'] = my_function
在渲染模板时,我调用
template = env.get_template('my_template.html')
template.render({'my_var': 'some_value'})
模板可能类似于
... some html here
{{ my_function }}
... some more html
这实际上并不是 return“你好”,而只是 empty/blank。
我通过传入一个虚拟变量设法得到它
@jinja2.contextfilter
def my_function(context, value):
.... code is the same
然后在模板中,我用 {{ 'hi' | my_function }}
调用它。但显然这只是一种 hack,并不是很理想。
所以我的问题是,如何调用仅将上下文作为参数的 jinja2 过滤器函数?我试过 {{ my_function() }}
return 错误 UndefinedError: 'my_function' is undefined
和 {{ | my_function }}, which returns the error
TemplateSyntaxError: unexpected '|'`
或者我应该使用其他一些 jinja2 构造?
编辑:我怀疑 jinja2 使用 |
来识别过滤器和变量,因为我没有 |
,所以它试图只渲染变量 my_function
来自上下文,因为它不存在于上下文中,所以它只输出一个空字符串。
Jinja2 调用这些函数 global functions(如 range()
),而不是过滤器。只需在这一行中将 filters
更改为 globals
:
env.globals['my_function'] = my_function
然后您可以在模板中调用您的函数:{{ my_function() }}
。