简体   繁体   English

如何防止Django的label_tag函数转义标签?

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

Example: 例:

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

Even calling mark_safe(example.label) before label_tag() does not prevent Django from escaping the HTML. 甚至在label_tag() mark_safe(example.label)之前调用mark_safe(example.label)也不会阻止Django转义HTML。 How can I get label_tag() to return unescaped labels? 如何让label_tag()返回非转义标签?

There is a comment in the code for 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.

So 所以

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

Should work.. I can't see another way around this problem 应该工作..我看不出另一种解决这个问题的方法

Try this: 尝试这个:

            from HTMLParser import HTMLParser

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

You have to mark the label as safe when you define the field. 定义字段时,必须将标签标记为安全。

class MyForm(forms.Form):

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

Example: 例:

>>> 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