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