質問

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