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

梦想的初衷 提交于 2020-08-07 07:53:29

问题


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

My problem

I get the output in raw html like so

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

instead of

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.

The idea

The idea is to get the text and create different paragraph for each part of the list created after the split so the text can be formatted pretty and tightty


回答1:


To disable autoescape you can use mark_safe method:

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:


This is explicitly covered in the documentation: Filters and auto-escaping.

You need to mark the output as safe.

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


来源:https://stackoverflow.com/questions/51986727/django-filters-to-return-html-that-will-be-rendered-in-the-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!