I have categories of cities and states set up as parents and children, for example:

  - Los Angeles
  - San Francisco

New York
  - New York City

When I use:

{% for place in entry.location %}
  {{ place }}
{% endfor %}

it returns to me the city state (for example: "Los Angeles California"). How can I separate out the parent and child? Ideally, I want to do something like this:

{{ place.child }}, {{ place.parent }}



If you have a 2-level category, and you select one of the nested categories (Los Angeles), what you get in your entry is Los Angeles and its parent (California). There is no way to have Los Angeles without also California, though you can have California without Los Angeles. Anyway, that for loop {% for place in entry.location %} will loop over both of them.

One way to be more explicit about the cities and the states is to loop over just the cities using level to fetch only the categories at a specific level in the category, and then for each city, fetch its ancestors with ancestorOf. Your code would look like this:

{% for city in entry.location.level(2) %}
  {% for state in craft.categories.ancestorOf(city) %}
    {{ state.title }}
  {% endfor %}
{% endfor %}
  • Excellent. Thanks Marion - this worked great! Appreciate it. – hidace Jul 22 '16 at 20:32

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.