twigtwig-filter

Twig strip tags but keep (or add) spaces between block-level elements


Consider the following HTML string:

{% set html = '<h2>Neo praemitto velit.</h2><p>Caecus metuo proprius.</p><p>At nobis plaga tego.</p>' %}

I run striptags() on that string:

{{ html|striptags() }}

Current output:

Neo praemitto velit.Caecus metuo proprius.At nobis plaga tego.

Expected output:

Neo praemitto velit. Caecus metuo proprius. At nobis plaga tego.

Question:

Is there an easy way to keep (or add) spaces in between the multiple closing and opening <p> and other block-level tags (like <h2>, etc.) that imply a line break?

I could probably do a search/replace afterwards with a regex to find . followed by any non whitespace character and add the space myself but that sounds like overkill. How would you do it?

I am using Twig 3.8.0 if that matters.


Solution

  • Twig has no built-in filters that can achieve what you want, however you could use some strings functions to get the desired effect

    {{ html|replace({
        '</h1>': ' ',
        '</h2>': ' ',
        '</h3>': ' ',
        '</h4>': ' ',
        '</h5>': ' ',
        '</h6>': ' ',
        '</p>': ' ',    
    }) | striptags }}
    

    demo


    If you need this on more than one place consider adding a (custom) filter to twig, e.g.

    $filter = new \Twig\TwigFilter('replace_html', function ($string) {
        return strip_tags(str_replace(['</h1>', '</h2>', '</h3>', '</h4>', '</h5>', '</h6>', '</p>',], ' ', $string));
    });
    
    
    $twig = new \Twig\Environment($loader);
    $twig->addFilter($filter);
    
    
    {{ html | replace_html }}