Search code examples
twigtwig-filter

Raw filter still converting & to & in the source


I'm trying to use the raw filter on Twig, but it's still converting & to & in the source.

so it's outputting ’ instead of ’

{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ "’"  %}
{% else %}
    {% set pluralLocationName  = entry.title ~ "’"  ~ "s" %}
{% endif %}
{% if entry.title|last == "s" %}
    {% set pluralLocationName  = entry.title ~ ("&"|raw) ~ "rsquo;" %}
{% else %}
    {% set pluralLocationName  = entry.title ~ ("&"|raw) ~ "rsquo;" ~ "s" %}
{% endif %}

edit: realizing i should have said "possessive" instead of "plural" :)


Solution

  • The filter raw is meant to output content. You can't store content marked as safe in a variable. This mean you need to add raw to your output, not the input

    {% if entry.title|last == "s" %}
        {% set pluralLocationName  = entry.title ~ "’"  %}
    {% else %}
        {% set pluralLocationName  = entry.title ~ "’"  ~ "s" %}
    {% endif %}
    
    {{ pluralLocationName | raw }}
    

    Same thing applies when you print the variable directly, instead of storing it in a variable. There you would need to wrap the full string in parentheses in order to make this work.

    The reason is the that filter will be executed first, thus marking &ruqou; as safe, but as soon as you concat the string, it will be marked as unsafe content again.

    {% if entry.title|last == "s" %}
        {{ (entry.title ~ "’")|raw  }}
    {% else %}
        {{ (entry.title ~ "’"  ~ "s")|raw }}
    {% endif %}
    

    sidenote You may want to make your snippet shorter like this

    {% set pluralLocationName  = entry.title ~ "’"  ~ (entry.title|last != 's' ? 's') %}
    {{ pluralLocationName | raw }}
    

    demo