I have a Matrix block with a text field and an Assets field. The text field has a Markdown filter applied to it.
I'd like the content owner to be able to enter a placeholder reference to one of the images uploaded to the sibling Assets field.
For example, when the template processes…
This is a **paragraph**.
%%img2%%
This is some more text.
…then %%img2%%
(or some such syntax that won't conflict with Markdown) gets replaced with the HTML generated for the second image by the relevant Assets query running in the template.
I've done things like this before with MXjumper and ExpressionEngine but am pretty new to Craft and not sure how to go about it.
I figure I need to:
- Set a dynamically named variable (because I don't know in advance how many images are in the image field)
- Use replace on the text field, but the replace statement should incorporate dynamically named search strings and the replacements would be the variables named at step 1 not strings.
Really not sure how to execute either of these 2 steps in Twig.
Would something like the following work for step1?
{% for img in sectionImages %}
{% set n %}{{ loop.index }}{% endset %}
{% set img ~ n %}
<figure>
<img src="{{ img.url }}" alt="{{ img }}">
{% if img.caption|length %}
<figcaption>
<span{{ img.caption }}</span>
</figcaption>
{% endif %}
</figure>
{% endset %}
{% endfor %}
And what then for step 2…
{{ block.sectionText|markdown|replace('%%img' ~ n ~ '%%': img ~ n) }}
My step 1 code feels like it's close but I suspect it's not right. And in any case I feel sure my step 2 code is further off from what's needed.
I think maybe I need to be storing img
as key|value pairs in an array and working with that somehow.
Any pointers much appreciated.