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?
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