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

标签 python django jinja2

我正在尝试将 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.

关于python - Django:如何将 jinja2 变量注入(inject)模板标签然后返回输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478260/

相关文章:

python - 在python中使用多线程读取txt文件

python - 如何在 git 中使用 python 和 dulwich 获取标签列表并创建新标签?

python - 将 y 轴格式化为百分比

python - 当减数为 None 时,使用减法运算符的 Django 注释返回 None

python - 获取 Jinja2 中的当前语言环境

python - 如何使用 selenium python 检索元素的所有 css 属性?

python - 在 URLConf 中定义嵌套 namespace ,用于反转 Django URL——有人有令人信服的例子吗?

django.core.exceptions.ImproperlyConfigured : WSGI application '{project_name}.wsgi.application' could not be loaded; Error importing module

jinja2 - Jinja - 当值超过指定的字段宽度时如何强制截断

python - 为什么我的 python GAE create_login_url 将用户重定向到 Google 设置个人信息页面