3

I'd like to use a tokenised image replacement technique which is commonly adopted in ExpressionEngine. This is where the author can add image tokens such as {image_1}, {image_2} etc into their content, and these get replaced by images defined in a matrix in the same publish form (with additional information such as image size etc). What technique can I use to achieve this?

3
  • 1
    This generally isn't necessary in Craft. You can use a Matrix Field and combination of Matrix Blocks to build advanced content with flexible images. This is really the best way to go if it's an option. That said, if you really needed what you've described, you could possibly do so with outputting your Rich Text field with Twig's template_from_string function and looping through your tokens field with the replace filter or something like that. I'm not posting this as an answer as I haven't tested this. Jul 26 '14 at 15:02
  • @Ben the Matrix part of your comment alone is worth an actual answer, that I'd tag as accepted if this was my question.
    – carlcs
    Jul 26 '14 at 15:29
  • Ok @ChristianSeelbach, you talked me into it =) Jul 26 '14 at 16:10
3

If you need to do something like the image below. The best option is to set the content as a variable and use the replace() filter to replace the tokens tags. Finally, use autoescape pair tag to output the content.

Not an elegant solution, but it works for me ;)

{# #############
        Field names
        -----
        Body: f_body
        Assets:
            f_media
                position
                media (assets)
############# #}


{% block content %}

    {% set body = entry.f_body|raw %}

    {% for item in entry.f_media %}
        {% if item.type == 'assets' %}
            {% set name = '{image_' ~ loop.index ~ '}' %} # name of token to replace
            {% set image = item.media[0].getUrl() %} # image path
            {% set imageElement = '<img src="' ~ image ~ '" class="' ~ item.position ~ '" />'  %} # image element

            {% set body = body|replace(name, imageElement) %}
        {% endif %}
    {% endfor %}


    {% autoescape false %}
        {{ body }}
    {% endautoescape %}

{% endblock %}

ps: This is something I came up quickly, needs bit of refactoring obvs.

Image replacement technique

2
6

This generally isn't necessary in Craft. You can use a Matrix Field and combination of Matrix Blocks to build advanced content with flexible images. This is really the best way to go if it's an option.

0

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.