bool.dev
bool.dev

Reputation: 17478

Apply safe filter to concatenated html string

I have been trying to do this:

{% set error_message = '<span class="help-inline">' + field.errors[0]|e + '</span>' %}
{# ... code ... #}
{{ error_message|safe }}

Trying to get this output in html:

<span class="help-inline">Some message</span>'

However the html is escaped and I get the above printed out as a string.

So question is how to mark a concatenated string as safe in Jinja2 ?


Current output (firebug):

span as html encoded string

Expected output:

correct html output


Update: Tried this but didn't work:

{% autoescape false %}
    {{ error_message|safe }}
    {# also tried without safe #}
{% endautoescape %}

Upvotes: 3

Views: 340

Answers (1)

bool.dev
bool.dev

Reputation: 17478

Marking each part string of the concatenation as safe however gives the desired output:

{% set error_message = '<span class="help-inline">'|safe + field.errors[0]|e + '</span>'|safe %}

OR slightly better:

{% set error_message = ('<span class="help-inline">' ~ field.errors[0]|e ~ '</span>')|safe %}

(combined safe filter for entire string concatenated with ~ instead. + doesn't work for this)

Upvotes: 1

Related Questions