如何显示带有 HTML-标记的文本? (我用的是ckeditor)
How to display text with HTML-markup? (I use ckeditor)
我听说过过滤器 |safe
,但如果我理解正确的话,那是不安全的,并且会创建一个用于注入的后门。
使用格式化文本显示完整帖子的替代方法是什么?
我认为当你不使用 |safe
的过滤器时,输出应该 return 仅作为带有 html 标记 的文本(不呈现为 html 输出).
但是,如果您需要排除一些危险的标签,例如<script>location.reload()</script>
,您需要使用自定义模板标签过滤器来处理它..
我从 那里得到了很好的回答,来自 BeautifulSoup
。
from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape
register = template.Library()
INVALID_TAGS = ['script',]
def clean_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name in INVALID_TAGS:
# tag.hidden = True # you also can use this.
tag.replaceWith(escape(tag))
return soup.renderContents()
# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>')
# output:
# <html><body><h1>This is heading</h1> and this one is xss injection <script>location.reload()</script></body></html>
@register.filter
def safe_exclude(text):
# eg: {{ post.description|safe_exclude|safe }}
return clean_html(text)
希望有用..
我听说过过滤器 |safe
,但如果我理解正确的话,那是不安全的,并且会创建一个用于注入的后门。
使用格式化文本显示完整帖子的替代方法是什么?
我认为当你不使用 |safe
的过滤器时,输出应该 return 仅作为带有 html 标记 的文本(不呈现为 html 输出).
但是,如果您需要排除一些危险的标签,例如<script>location.reload()</script>
,您需要使用自定义模板标签过滤器来处理它..
我从 那里得到了很好的回答,来自 BeautifulSoup
。
from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape
register = template.Library()
INVALID_TAGS = ['script',]
def clean_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name in INVALID_TAGS:
# tag.hidden = True # you also can use this.
tag.replaceWith(escape(tag))
return soup.renderContents()
# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>')
# output:
# <html><body><h1>This is heading</h1> and this one is xss injection <script>location.reload()</script></body></html>
@register.filter
def safe_exclude(text):
# eg: {{ post.description|safe_exclude|safe }}
return clean_html(text)
希望有用..