簡體   English   中英

如何防止Django的label_tag函數轉義標簽?

[英]How to prevent Django's label_tag function from escaping the label?

例:

>>> example.label
&#x3bb;<sub>blabla</sub>
>>> example.label_tag()
[...]&amp;#x3bb;&lt;blabla&gt;[...]

甚至在label_tag() mark_safe(example.label)之前調用mark_safe(example.label)也不會阻止Django轉義HTML。 如何讓label_tag()返回非轉義標簽?

label_tag代碼中有label_tag

Wraps the given contents in a <label>, if the field has an ID attribute.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.

所以

example.label_tag(contents=mark_safe(example.label))

應該工作..我看不出另一種解決這個問題的方法

嘗試這個:

            from HTMLParser import HTMLParser

            h = HTMLParser()
            unescaped = h.unescape(example.label_tag())
            print unescaped

定義字段時,必須將標簽標記為安全。

class MyForm(forms.Form):

    example = forms.Field(label=mark_safe('&#x3bb;<sub>blabla</sub>'))

例:

>>> f = MyForm({'example': 'foo'})
>>> str(f)
'<tr><th><label for="id_example">&#x3bb;<sub>blabla</sub>:</label></th><td><input id="id_example" name="example" type="text" value="foo" /></td></tr>'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM