Django 过滤器以返回将在模板中呈现的 HTML

Thu*_*orn 8 django django-templates django-filters

我的_文本

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.'''
Run Code Online (Sandbox Code Playgroud)

我的过滤器

@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
Run Code Online (Sandbox Code Playgroud)

我的问题

我像这样得到原始 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>
Run Code Online (Sandbox Code Playgroud)

代替

模板系统分两步工作:编译和渲染。一个编译好的模板就是一个 Node 对象列表。

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

想法

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

nev*_*ner 16

要禁用自动转义,您可以使用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)
Run Code Online (Sandbox Code Playgroud)


Dan*_*man 7

这在文档中明确涵盖:过滤器和自动转义

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

from django.utils.safestring import mark_safe
...
return mark_safe(text)
Run Code Online (Sandbox Code Playgroud)