如何使用HTML标记显示文本? (我用ckeditor) [英] How to display text with HTML-markup? (I use ckeditor)
问题描述
我听说过过滤器 | safe
,但是如果我理解正确,这是不安全的,并为注射创建一个后门。
I heard about the filter |safe
, but if I understood correctly, that's unsafe and creates a backdoor for injections.
使用格式化文本显示完整帖子的替代方法是什么?
What are the alternatives to display full posts with formatted text?
推荐答案
p>我认为当你不使用 | safe
的过滤器时,输出应该只返回html标记的文本(不渲染为html输出)。
I think when you not use the filter of |safe
, then output should return as text only with html markup (not rendered as html output).
但是,如果您需要排除一些危险的标签,例如< script> location.reload()< / script> / code>,你需要使用自定义模板过滤器来处理它。
But, if you need to exclude some dangerous tags such as <script>location.reload()</script>
, you need to handle it with custom templatetag filter..
我从以下方面得到了很好的答案: https://stackoverflow.com/a/699483/6396981 ,通过 BeautifulSoup
。
I got good answer from: https://stackoverflow.com/a/699483/6396981, via 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)
希望它有用..
这篇关于如何使用HTML标记显示文本? (我用ckeditor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!