I have a rich text (redactor field) that I'm using striptags on to remove the html markup from the front end. However I noticed for links it whips out the link and the text in between. Is this something I can fix with a regular expression? Can you even do that with a twig filter? If so does anyone have an example?

Here is my code:

{% set articleText = myFirstMatrixBlockWithType.blogArticleText %}
{% if articleText | length > 200 %}
    {% set articleTextTrim = articleText | slice(0, 200) ~ '...' %}
    {{ articleTextTrim | striptags }}
{% else %}
    {{ articleText | striptags }} 
{% endif %}

Actually, excluding certain tags from being removed is built into the striptags filter.

You can use it like this:

{{ articleTextTrim | striptags('<a>') }}
  • but then it outputs as html like <a href="www.example.com">link to something</a> I was hope to keep the "link to something" text but remove the html markup. May 15 '18 at 15:46
  • A raw filer should stop escaping the link. {{ articleTextTrim | striptags('<a>') | raw }}
    – Willhaus
    Jul 10 '19 at 21:22

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.