3

Is there a way to output the first image of a rich text field?

At the moment the template code is as simple as:

{{ entry.body }}

The purpose is so that I can use the image in the meta section of the template. If there is no easy solution I could change it to be a Matrix field.

4

I think the best way to do this, is by creating a small Twig extension plugin that uses PHP's html parser to find the first occurrence of an IMG tag and return the src of that tag to your template. This is a step-by-step explanation of how to create your very own Twig filter.

You could then to this:

{{ entry.body | firstImageSrc }}

And it would return the url you need.

The easiest way, however, is to add an asset field to your Entry Type's field layout and choose a file manually.

  • Just discovered you can do this with the hacksaw plugin: {{ article.articleText|hacksaw(hack='image')|striptags('<img>')|raw }} – Martin Sep 26 '17 at 15:48

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.