I want to strip every headline tag from all Rich Text fields site-wide.

So I thought about adding a replace filter.

But since this will be site wide I wanted to write the replace rules in a variable:

{% set replaceHeadline = '"<h1>" : "<p>", "</h1>" : "</p>"' %}
{{ entry.richText | replace({replaceHeadline}) | raw }}

This produces the error:

A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "}" ("punctuation" expected with value ":").

Is this not possible? Is concatenation with ~ somehow the way to go?

Is there a more sane approach to stripping all headline tags from Rich Text fields?


You'd have to store the complete array into the variable

{% set replaceHeadline = {'<h1>': '<p>', '</h1>': '</p>'} %}
{{ entry.richText|replace(replaceHeadline)|raw }}

But instead of storing that variable I'd probably just create a macro for that snippet.


{% macro formatRichText(string) %}
    {{- string|replace({
        '<h1>': '<p>',
        '</h1>': '</p>'
    })|raw }}
{% endmacro %}


{% import '_includes/macros' as macros %}

You can now use that helper macro everywhere in your templates

{{ macros.formatRichText(entry.richText) }}

Another recommendation, have a look at the RetconHTML plugin, a nice little plugin to manipulate HTML with Twig.

{{ string|retconChange('h1', 'p') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.