문제

Django has a template tag that allows you to remove certain html tags from being displayed in stored data.

The django documentation gives an example. Any b or span tags are removed. https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#removetags

{{ value|removetags:"b span"|safe }}

However, I'm wondering if there is a good way to do the inverse. For example, blacklist all tags except for tags specified. In my case, I just want to allow bold and italic tags.

도움이 되었습니까?

해결책

Write your own template tag using bleach.

다른 팁

You can write your own template tag based on original removetags and this regexp:

>>> import re
>>> tags = ['b', 'i']
>>> tags_re = u'(%s)' % u'|'.join(tags)
>>> striptags_re = re.compile(ur'</(?!{0}).*?>|<(?!/)(?!{0}).*?>'.format(tags_re), re.U)
>>> value = '<b>foo</b><i><p>bar</b>'
>>> striptags_re.sub(u'', value)
u'<b>foo</b><i>bar</b>'
>>> value = '<b>foo</b><p>bar</p>'
>>> striptags_re.sub(u'', value)
u'<b>foo</b>bar'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top