Reputation: 59
Is it possible to assign a variable and use that variable in the for loop statement?
I'm trying to place a collection of products in a blog without having to create a new for loop for each article that needs a collection.
What I've done is using the article's tags and splitting just before the collection handle so I can inject it in the for loop, but it's not quite working dynamically yet...
Here's what I've done.. I added in the article tags
collection_some-page-handleThen in the article.liquid
{% for tag in article.tags %}
{% assign tagMap = tag | split: '_' %}
{% if tagMap.first == 'collection' %}
{% assign collectionName = tagMap.last %}
{% endif %}
{% endfor %}
{{collectionName}} <!-- this shows the handle of the collection -->
{% for product in collections.collectionName.products limit: 8%}
<div class="productWrap">
<a href="{{ product.url}}"><img src="{{ product.featured_image | product_img_url: 'medium' }}" alt=""></a>
<a href="{{product.url}}"><p class="product_title" style="border-top:1px solid #efefef;">{{ product.title | split: ' - ' | first }}</p></a>
</div>
{%endfor%}
Now if i try to put the variable in the for loop it doesnt work, but of course if i put the actual handle it works. Is there a way to do it dynamically?
Upvotes: 0
Views: 3371
Reputation: 12933
Instead of using collections.collectionName
use collections[collectionName]
.
This should fix your issue if your variable has the proper handle indeed.
To clarify when you use collections.collectionName
you say - "Get me a collection that have handle collectionName`.
When you use collections[collectionName]
you say - "Get me a collection using the variable collectionName
as a handle."
Upvotes: 3