我正在嘗試在我的服務中渲染一個 jinja2 模板(不使用燒瓶,只使用純 jinja2 并構建一個 jinja2 環境。
假設我定義了以下過濾器
import jinja2
@jinja2.contextfilter
def my_function(context):
if context.get('my_var'):
return "hello"
else:
return "world"
超級簡化的示例,但重點是我有一些邏輯,可以根據傳遞到背景關系中的某個變數有條件地回傳一個值。
另外,我正在使用 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
這實際上并沒有回傳“你好”,而只是空/空白。
我設法通過傳入一個虛擬變數來得到它
@jinja2.contextfilter
def my_function(context, value):
.... code is the same
然后在模板中,我用{{ 'hi' | my_function }}. 但顯然這只是一個 hack,并不是很理想。
So my question is, how can I call a jinja2 filter function that only takes the context in as an argument? I've tried {{ my_function() }} which returns the error UndefinedError: 'my_function' is undefined, and {{ | my_function }}, which returns the error TemplateSyntaxError: unexpected '|'`
Or is there some other jinja2 construct I should be using?
Edit: my suspicion is that jinja2 uses the | to identify a filter vs a variable, and since I don't have |, then it tries to just render the variable my_function from the context, and since it doesn't exist in the context, it just outputs an empty string.
uj5u.com熱心網友回復:
Jinja2 將這類函式稱為全域函式(如range()),而不是過濾器。只需更改filters為globals這一行:
env.globals['my_function'] = my_function
然后你可以在模板中呼叫你的函式:{{ my_function() }}.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/440107.html
