1

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

California
  - 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 }}

Thanks.

1 Answer 1

4

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) %}
  {{city.title}},
  {% for state in craft.categories.ancestorOf(city) %}
    {{ state.title }}
  {% endfor %}
{% endfor %}
1
  • Excellent. Thanks Marion - this worked great! Appreciate it.
    – dace
    Commented Jul 22, 2016 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.