简体   繁体   中英

Render WTForms SelectField options with embedded HTML in Jinja

I am trying to create an option in a SelectField that uses an embedded span in the label. However, the tag is escaped and displayed literally in the field.

I've tried Embed HTML tag in Flask WTForms field but it doesn't work in this case (likely because the text that needs to be escaped is inside a list).

Is it possible to render the HTML unescapped in the option label without writing my own renderer?

class myForm(Form):
    myChoices = [
        ('0','Select an option <span class="caret"></span>'),
        ('1','Option 1'),
        ('2','Option 2')
    ]
    optionSelect = SelectField('Select', choices=myChoices, validators=[Required()])

Similar to the question you linked, you need to let Jinja know that the value you're rendering is trusted and shouldn't be escaped. Since you don't directly control the rendering of the options, you can't use the |safe filter and need to do this when defining the value instead. Use the Markup class to mark a string as safe in Python.

from jinja2 import Markup

('0', Markup('Select an option <span class="caret"></span>')),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM