简体   繁体   English

Django-使用Bleach清理Markdown

[英]Django - Rendering Markdown Sanitizied with Bleach

When I do markdown(text), without bleach, I get the desired result (raw): 当我做markdown(text),没有漂白的时候,我得到了想要的结果(原始):

<p>blah</p>

and it displays correctly as: 并且它正确显示为:

blah

where the "p" tags are rendered correctly as a paragraph block. 其中“ p”标签正确显示为段落块。

When I do bleach.clean(markdown.markdown(text)), I get (raw): 当我做bleach.clean(markdown.markdown(text))时,我得到(原始):

&lt;p&gt;blah&lt;/p&gt;

and it displays incorrectly as: 并且它错误地显示为:

<p>blah</p>

where the "p" tags are part of the text and not an HTML paragraph block. 其中“ p”标记是文本的一部分,而不是HTML段落块。

You need to mark the bleach ed HTML as safe 您需要将bleach HTML标记为安全

from django.utils.safestring import mark_safe

...
    return mark_safe(bleach.clean(markdown.markdown(text)))

But, there is also django-bleach that provides integration with Django and ready-made tags to use bleach in Django. 但是,还有django-bleach提供与Django的集成以及现成的标签以在Django中使用漂白。

{% load markdown_deux_tags bleach_tags %}
{{ view_user.profile.about|markdown:"user"|bleach }}

In settings.py you can tell django-bleach what tags are okay settings.py您可以告诉django-bleach哪些标签可以

BLEACH_ALLOWED_TAGS = ['h1', 'h2', 'p', 'b', 'i', 'strong', 'a']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']
BLEACH_ALLOWED_STYLES = ['font-family', 'font-weight']
BLEACH_STRIP_TAGS = True

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM