Django:我如何将jinja2变量注入模板标记中,然后返回outpu

2024-10-01 09:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个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)

我希望输入变量被呈现到页面中。你知道吗

任何建议都会有帮助的谢谢!你知道吗


Tags: 函数testregisterjinja2valuemyfunctiontemplate
1条回答
网友
1楼 · 发布于 2024-10-01 09:19:06

这不是一个模板标记,而是一个模板过滤器(注意register.filter(..)),您只需使用垂直条进行过滤:

{{ test.recordtype|my_function }}

这在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.

相关问题 更多 >