1

I've got two entry types: blog and job. Each has a category field but different category groups: blogCategories and jobCategories. I would like to write a Twig include to accept either a blog or a job and display its categories like:

<h2>{{ entry.title }}</h2>
<p>{{ entry.category.all()|column('title')|join(', ') }}</p>

Is there any way to do this? I tried creating two fields, both called categories but the field handle has to be unique. Is there such a thing as a field alias?

2

You need two different fields since you can only select one category group per category field. As you said, having two fields with the same name isn't possible. One way to work around this would be to add a behaviour that checks the entry type and returns the categories from the corresponding field (i.e. jobCategories for job entries and blogCategories for blog entries).

However, this is more complicated than it needs to be. You can just define a macro and pass it the appropriate field depending on the template:

{# macros/macros.twig #}
{% macro category_list(categoryQuery) %}
    <p>{{ categoryQuery.all()|column('title')|join(', ') }}</p>
{% endmacro %}


{# blog/_entry.twig #}
{% from "macros/macros.twig" import category_list %}

<h2>{{ entry.title }}</h2>
<p>{{ category_list(entry.blogCategories) }}</p>


{# job/_entry.twig #}
{% from "macros/macros.twig" import category_list %}

<h2>{{ entry.title }}</h2>
<p>{{ category_list(entry.jobCategories) }}</p>

If you have a single entry template for both entry types, you can also check the different fields inside the macro:

{# macros/macros.twig #}
{% macro category_list(entry) %}
    {% switch entry.type.handle %}
        {% case "job" %}
            {% set categories = entry.jobCategories.all() %}
        {% case "blog" %}
            {% set categories = entry.blogCategories.all() %}
        {% default %}
            {% set categories = [] %}
    {% endswitch %}
    <p>{{ categories|column('title')|join(', ') }}</p>
{% endmacro %}


{# entry/_entry.twig #}
{% from "macros/macros.twig" import category_list %}

<h2>{{ entry.title }}</h2>
<p>{{ category_list(entry) }}</p>

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.