I have a section called “products” that has an asset field called “product-docs”. The assets are pdf files that have a Category field. Each product can have many different types of documents; to make it easier to find the document you want (on a product page), there are five different Document Categories, each of which has a number of Document Types, e.g.:

Installation Guides (Document Category) Mounting instructions (Document Type) Wiring Instructions (Document Type)

What I want to do is to show all documents for a given product, grouped by Document Category. If I fetch the data for the document category field it returns a string that comprises both the Document Category and the Document Sub Category. Here is an example of what I am trying to accomplish: https://www.ruskin.com/model/aiq-td-50 (docs are grouped by category in the section labelled Additional Resources)

How can I query the category field so that I can access the Document Category and then all the related Sub Categories? I tried using .level1, but that does not work.

1 Answer 1


I’m assuming you want to do this in Twig rather than PHP, since you haven’t specified nor have you provided any code.

First, fetch all assets, eager-loading the categories.

{% set assets = entry.product-docs

Then use the group filter to group the assets by the category title.

{% set assetGroups = assets|group(asset => asset.category-field-handle.one().title) %}

Finally, output the assets, grouped by category title:

{% for categoryTitle, assetGroup in assetGroups %}
    {{ categoryTitle }}

    {% for asset in assetGroup %}
        {{ asset.title }}
    {% endfor %}
{% endfor %}
  • A thousand thanks, Ben - worked perfectly! Only minor change was to use asset.category-field-handle[0] instead of .one().
    – Roi Agneta
    Feb 27, 2023 at 17:42
  • 1
    .one() should work fine in Craft 4.
    – Ben Croker
    Feb 27, 2023 at 17:55
  • Good to know - in the process of moving the site from Craft 3 to Craft 4. Thanks again, Ben - much appreciated!
    – Roi Agneta
    Feb 27, 2023 at 18:02

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.