Ad

How To Grab What Collection A Product Belongs To?

- 1 answer

i am trying to get the collection a product belongs to when running a loop but all it returns is collectiondrop as the output. example:

{% for product in collections.all.products %}
{{ product.collections }} //each product belongs to one collection only.
{% endfor %}

this is on a products page, such as related products. so when i try something like this:

{{ product.url | within:collection }}

it grabs the current collection that im viewing for a product and it has no corelation to the product that was listed. so the resulting url becomes

/product/item-name

instead of

/collection/some-name/product/some-product-name

which is what im looking for.

Ad

Answer

Even if products belongs to a single collection, the collection object is still an array, so you should call it like so:

{% for product in collections.all.products %}
{{ product.collections[0] }}
{% endfor %}

Have in mind that you must specify what you want from the collection or it will return collection drop, so for example {{ product.collections[0].url }} will do OK.

When you are stuck in such way use the json filter to check what is the object returning ( when in this example it will probably not allow you to see the object json ).

Ad
source: stackoverflow.com
Ad