gpt4 book ai didi

python - 防止在 Django 中自动转义自定义模板标签

转载 作者:行者123 更新时间:2023-12-02 17:16:16 25 4
gpt4 key购买 nike

我正在将我的旧项目升级到最新版本的 python/django,但在使用自定义模板标签时遇到了问题。

模板标签定义:

from django import template
register = template.Library()

def my_tag(*args) -> str:
""" returns html code """

register.simple_tag(lambda *x: my_tag("hello world", *x), name='my_tag')

标签使用示例:

{% my_tag "this no longer works, this autoescapes my code" %}

如何修改我的标签定义以防止自动转义,这样我就不必修改模板:

{% autoescape off %}{% my_tag "workaround, this doesn't autoescape html" %}{% endautoescape %}

最佳答案

您可以使用 mark_safe 将结果标记为安全方法:

from django.utils.safestring import mark_safe
def my_tag(*args) -> str:
return mark_safe(result)

关于python - 防止在 Django 中自动转义自定义模板标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com