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