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?
Asked
Active
Viewed 212 times
1 Answers
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 %}
carlcs
- 36,220
- 5
- 62
- 139
-
Thank you... my code is now like this and works. {% set imageExists = block.textArea|retconOnly('img')|length %} {% set classAttr = imageExists ? 'with-image' : '' %}{{ block.textArea|retconUnwrap('img') }}– Martin Apr 28 '17 at 10:09