Skip to main content
 首页 » 编程设计

python之Django:如何将 jinja2 变量注入(inject)模板标签然后返回输出

2024年11月01日39jackei

我正在尝试将 jinja2 变量作为参数传递给函数,但我不确定这样做的语法或方法。

我试过在 jinja2 函数调用中包含引用,但这没有用。

我已经测试了这个函数,它使用一个简单的字符串“test”并且值在页面中呈现。

HTML 部分

... 
<tbody> 
{% for test in test_records %} 
    <tr> 
        <td class="trGrey"> {{ test.id }} </td> 
        <td class="trGrey"> {{ test.testname }} </td> 
        <td class="trGrey"> {{ test.created }} </td> 
        <td class="trGrey"> {{ test.recordtype }} </td> 
        <td class="trGrey"> {{ {{ test.recordtype }}|my_function }} </td> 
    </tr> 
{% endfor %} 
</tbody> 
... 

Python 文件

from django import template 
register = template.Library() 
 
def my_function(value): 
    if value: 
        return value 
    return '' 
 
register.filter('my_function', my_function) 

我希望将输入变量呈现给页面。

任何建议都会有帮助,谢谢!

请您参考如下方法:

这不是模板标签,而是模板过滤器(注意 register.<i>filter</i>(..) ),您只需使用竖线进行过滤:

{{ test.recordtype<b>|my_function</b> }}

这在 Jinja documentation on filters 中有描述:

Variables can be modified by filters. Filters are separated from the variable by a pipe symbol (|) and may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.