Django 过滤到将在模板中呈现的 return HTML

Django filters to return HTML that will be rendered in the template

my_text

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.'''

my_filter

@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>

而不是

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.

想法

想法是获取文本并为拆分后创建的列表的每个部分创建不同的段落,这样文本的格式就可以漂亮了 和紧张

要禁用自动转义,您可以使用 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)

文档中明确涵盖了这一点:Filters and auto-escaping

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

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