1

I have a structure for different categories like salad, soup, main course and so on. Basically they share the same fields - but I want to be able to have dynamic singles based on those structures. For example I have a MainMenu-Single where I than can select entries from salads, soups, main courses and so on.

But is there a way to loop through all the fields in that single?

I tried:

{% for category in craft.entries.section('foodMenuCategories') %}
    {% if entry.{category} is defined %} 
       ...

Sadly that doesn't work.

  • Not sure I am understanding the question so I don't want to answer outright, but you shouldn't have curly brackets within your twig. So {% if entry.category is defined %} – AbbeyDesign Sep 17 '14 at 13:16
  • thats exacly my problem I have like ten different categories but they need exactly the same snippet and I want to automate the {% if entry.soup is defined %} {% if entry.salad is defined %} {% if entry.mainCourse is defined %} and so on – maxx Sep 17 '14 at 13:20
3

I think there's a few ways you can do this with twig.

You should be able to check whether the category slug exists as an attribute on the entry object:

{% for category in craft.categories.group('foodMenuCategories') %}
    {% if category.slug in entry.getAttributes|keys %} 
        ...

Or by using the category slug in an array accessor:

{% for category in craft.categories.group('foodMenuCategories') %}
    {% if entry[category.slug] is defined %}
       ...

Or whether the getAttribute() method on the entry model returns anything truthy for that handle:

{% for category in craft.categories.group('foodMenuCategories') %}
    {% if entry.getAttribute(category.slug) %} 
        ...

It's also important, that the slug is the same in every language!

| improve this answer | |
  • the .handle is only for categoryGroups so I have to use something different - but the idea is perfect – maxx Sep 17 '14 at 13:43

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.