3

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()])
Community
  • 1
  • 1

1 Answers1

1

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>')),
davidism
  • 121,510
  • 29
  • 395
  • 339