【问题标题】:Django filters to return HTML that will be rendered in the templateDjango 过滤器返回将在模板中呈现的 HTML
【发布时间】:2018-08-23 13:17:17
【问题描述】:

我的文本

my_text = '''The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects.

Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.'''

我的过滤器

@register.filter(is_safe=True)
def format_description(description):
    text = ''
    for i in description.split('\n'):
        text += ('<p class="site-description">' + i + '</p>')
    return text

我的问题

我得到原始 html 的输出,就像这样

 <p class="site-description">The template system works in a two-step process: compiling and rendering. A compiled template is, simply, a list of Node objects.</p><p class="site-description">    </p><p class="site-description">    Thus, to define a custom template tag, you specify how the raw template tag is converted into a Node (the compilation function), and what the node’s render() method does.</p>

而不是

模板系统分两步工作 过程:编译和渲染。一个编译的模板,简单来说,就是一个 Node 对象的列表。

因此,要定义自定义模板标签, 您指定如何将原始模板标签转换为节点( 编译函数),以及节点的 render() 方法的作用。

想法

这个想法是获取文本并为拆分后创建的列表的每个部分创建不同的段落,以便可以漂亮地格式化文本 又紧又紧

【问题讨论】:

  • 使用mark_safe

标签: django django-templates django-filters


【解决方案1】:

要禁用自动转义,您可以使用mark_safe 方法:

from django.utils.safestring import mark_safe

@register.filter(is_safe=True)
def format_description(description):
    text = ''
    for i in description.split('\n'):
        text += ('<p class="site-description">' + i + '</p>')
    return mark_safe(text)

【讨论】:

    【解决方案2】:

    这在文档中有明确的说明:Filters and auto-escaping

    您需要将输出标记为安全。

    from django.utils.safestring import mark_safe
    ...
    return mark_safe(text)
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2020-06-19
      • 2018-03-01
      • 2021-04-21
      • 1970-01-01
      • 2018-08-14
      • 2019-01-01
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多