1

I have a DIV wrapping a Rich Text field. I would like to add a class name to the DIV only if an image is present in the text field. Is there a way to check for an image?

3

You could use the in operator to search for a substring in your markup.

{% set imageExists = '<img' in entry.body.getRawContent() %}
{% set classAttr = imageExists ? 'with-image' : '' %}

<div class="{{ classAttr }}">
    {{ entry.body }}
</div>

Another, probably bit more reliable way to test for <img> elements is to use the Retcon plugin, which uses DOMdocument to parse the markup.

A combination of retconOnly and length filters should get you there.

{% set imageExists = entry.body|retconOnly('img')|length %}
  • Thank you... my code is now like this and works. {% set imageExists = block.textArea|retconOnly('img')|length %} {% set classAttr = imageExists ? 'with-image' : '' %} <div class="entryTxt {{ classAttr }}"> {{ block.textArea|retconUnwrap('img') }} </div> – Martin Apr 28 '17 at 10:09

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.