【问题标题】:Rendering a template variable as HTML将模板变量呈现为 HTML
【发布时间】:2019-06-25 20:45:17
【问题描述】:

我使用“消息”界面将消息传递给用户,如下所示:

request.user.message_set.create(message=message)

我想在我的 {{ message }} 变量中包含 html 并在不转义模板中的标记的情况下呈现它。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    如果您不想转义 HTML,请查看 safe 过滤器和 autoescape 标记:

    safe:

    {{ myhtml |safe }}
    

    autoescape:

    {% autoescape off %}
        {{ myhtml }}
    {% endautoescape %}
    

    【讨论】:

    • 如果您需要显示例如欧元 (€) 等货币符号,美元从视图中传递,这就是要走的路。
    • 请注意,它是autoescape off 而不是on。我犯了这个错误,后来才发现。
    【解决方案2】:

    如果您想对文本做一些更复杂的事情,您可以创建自己的过滤器并在返回 html 之前做一些魔术。 使用如下所示的模板标签文件:

    from django import template
    from django.utils.safestring import mark_safe
    
    register = template.Library()
    
    @register.filter
    def do_something(title, content):
    
        something = '<h1>%s</h1><p>%s</p>' % (title, content)
        return mark_safe(something)
    

    然后你可以在你的模板文件中添加这个

    <body>
    ...
        {{ title|do_something:content }}
    ...
    </body>
    

    这会给你一个很好的结果。

    【讨论】:

      【解决方案3】:

      使用autoescape 关闭 HTML 转义:

      {% autoescape off %}{{ message }}{% endautoescape %}
      

      【讨论】:

        【解决方案4】:

        您可以像这样在代码中呈现模板:

        from django.template import Context, Template
        t = Template('This is your <span>{{ message }}</span>.')
        
        c = Context({'message': 'Your message'})
        html = t.render(c)
        

        有关详细信息,请参阅Django docs。

        【讨论】:

        • 我想我在这里搞错了,但我现在留下答案。
        【解决方案5】:

        最简单的方法是使用safe 过滤器:

        {{ message|safe }}
        

        查看Django documentation for the safe filter 了解更多信息。

        【讨论】:

          【解决方案6】:

          无需在模板中使用过滤器或标签。 只需使用 format_html() 将变量转换为 html,Django 会自动为您的变量关闭转义。

          format_html("<h1>Hello</h1>")
          

          在这里查看https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html

          【讨论】:

          • from django.utils.html import format_html
          猜你喜欢
          • 2012-12-11
          • 1970-01-01
          • 2021-08-17
          • 1970-01-01
          • 2012-05-06
          • 2017-01-31
          相关资源
          最近更新 更多