1

How do I pass variables to a loop within an include?

This is my partial:

{% for photo in photos %}
    <img src="{{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }}"
{% endfor %}

I'm calling it from a template with this:

{% set projectEntries = craft.entries({
    section: 'project'
}) %}
{% set vars = {
    photos: projectEntries
    } 
%}
{% include "_partials/photo-tile.html" with vars %}

All well and good

but

What if I want to abstract this from my partial:

src="{{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }}"

In other words, I'd like to pass the src, {{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }} , into the partial but I don't know how!

If I try to do it from the template like this (through photoSrc), it fails, saying the 'photo' is undefined:

{% set vars = {
    section: "category",
    category: category,
    pageOneTitle:  categoryTitle,
    photos: projectEntries,
    photoSrc: photo.projectPhotos_photo_image.first().getUrl('projectThumbnail')
    } 
%}

Any tips?

1

You can't reference a variable (photo) created inside the partial loop outside the partial (and loop) – it doesn't exist yet – so what you're trying to achieve isn't possible.

What you could do, is to abstract the important bits, namely the field and transform handles:

{% set vars = {
    photos: projectEntries,
    photoField: 'projectPhotos_photo_image',
    photoTransform: 'projectThumbnail'
} %}
{% include "_partials/photo-tile.html" with vars %}

And inside your partial:

{% for photo in photos %}
   <img src="{{ photo[photoField].first().getUrl(photoTransform) }}" />
{% endfor %}

If that doesn't cut it, you'll probably want to use a macro:

{# Your macro file, e.g. /templates/_macros/photoTile.html #}
{% macro src(photo) %}
    {{ photo.projectPhotos_photo_image.first().getUrl('projectThumbnail') }}
{% endmacro %}

{# Inside your partial #}
{% from '_macros/photoTile' import src %}
{% for photo in photos %}
    <img src="{{- src(photo) -}}" />
{% endfor %}

(If you're wondering about the {{- -}} syntax in the above example, the dashes are just to remove whitespace from the rendered src string – you also wrap the code inside the macro in {% spaceless %}{% endspaceless %} tags.)

  • Thanks for the response. I tried your first idea and it failed. I think that the macro would work but this is a lot of hassle in an attempt to make a componentized, partial-based system. I'm going to experiment with vuejs.org – portnoy-the-elder Jan 23 '17 at 20:07

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.