1

What would be the best approach to have a list of categories (brands in my case.) and if an asset (image) exists that matches that brand name show that asset or instead show a placeholder image.

<ul>
{% for category in craft.categories.group('brands') %}
    <li>
        <a href="{{ category.url }}">
            <img src="{{ .. }}" />
        </a>
    </li>
{% endfor %}
</ul>
  • So with something along the lines of; {% for image in craft.assets.kind('brands') %} <li> <a href="{{ category.url }}"> <img src="{{ image.getUrl() }}" /> </a> </li></li> {% endfor %} But with an if statement there too, if it's exist use it, else a placeholder url for the src. – Kitsune May 21 '16 at 8:28
4

I would add the brand category field to the assets field set. This way you can add brands to images and use .relatedTo to find them.

<ul>
  {% for category in craft.categories.group( 'brands' ) %}
    // This will give you the first image that relates to the category, you could use .find() to get all images and then loop through them.
    {% set image = craft.assets.relatedTo( category ).first() %}

    <li>
      <a href="{{ category.url }}">
        {% if image|length %}
          <img src="{{ image.url }}" />
        {% else %}
          <img src="http://placehold.it/400x300" />
        {% endif %}
      </a>
    </li>
  {% endfor %}
</ul>
  • Perfect. Got what I needed and learned something new. Thank you Luke! – Kitsune May 21 '16 at 9:05
  • 1
    @kitsune what if you'd just add an asset field "logo" to the categories? That makes it possible to use the more convenient syntax myCategory.logo.first() to get a category's brand logo. Makes more sense from the data entry aswell, add logo, address, etc. to the brand category. – carlcs May 22 '16 at 9:36
  • 1
    I'd implement my way if there are many images related to a category but go with carlcs way if you only need a single image to be associated with a category. – Luke Pearce May 22 '16 at 10:37

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.