使用Jinja2 striptags过滤器时如何保留换行符' '?
Great question! The good news is that Jinja2's striptags filter doesn't remove newline characters (\n) by default—it only strips out HTML tags. So if your submitted content already includes actual newlines to separate paragraphs, using striptags alone will do exactly what you need.
Basic Case: Content Already Has Newlines
Suppose your input content looks like this:
<p>First paragraph with <em>emphasized</em> text.</p> Second paragraph with a <a href="#">link</a> that should be stripped.
Applying the striptags filter:
{{ submission_content|striptags }}
Will output:
First paragraph with emphasized text. Second paragraph with a link that should be stripped.
Perfect—newlines are preserved, all HTML tags are gone.
Handling HTML Line Breaks (e.g., <br>, <p>)
If your submission uses HTML elements like <br> or <p> to create line breaks instead of raw \n characters, you’ll want to convert those elements to actual newlines first before stripping tags. Otherwise, striptags will just remove the tags and merge your paragraphs together.
You can do this using Jinja2’s built-in replace filter chained with striptags:
{{ submission_content|replace('<br>', '\n')|replace('<br/>', '\n')|replace('</p>', '\n\n')|striptags }}
Let’s break this down:
replace('<br>', '\n')andreplace('<br/>', '\n'): Convert both standard and self-closing line break tags to newlines.replace('</p>', '\n\n'): Add two newlines after closing paragraph tags to maintain paragraph separation (adjust to one\nif you prefer tighter spacing).striptags: Finally, strip all remaining HTML tags.
Example input with HTML line breaks:
<p>First paragraph <br> with a line break.</p><p>Second paragraph here.</p>
After applying the chained filters, the output becomes:
First paragraph with a line break. Second paragraph here.
Bonus: Custom Filter for More Control
If you find yourself doing this often, you can create a custom Jinja2 filter to encapsulate this logic. For example, in Python:
from jinja2 import Environment def strip_tags_preserve_newlines(content): # Convert HTML line breaks to newlines first content = content.replace('<br>', '\n').replace('<br/>', '\n').replace('</p>', '\n\n') # Then strip tags return Environment().filters['striptags'](content) # Add the filter to your Jinja2 environment env = Environment() env.filters['strip_tags_preserve_newlines'] = strip_tags_preserve_newlines
Then use it in your templates like:
{{ submission_content|strip_tags_preserve_newlines }}
内容的提问来源于stack exchange,提问作者rogwan

