1

I have entries, which can have several categories. These categories are in different categorie groups.

Now if i show an entry page, i want to display i certain html block based on a specific category, the entry has or not.

i tried this, but its not working, i think i get the relatedTo thing wrong:

//i loop through all the categories in my group

{% for category in craft.categories.group('catGroup1') %}

//the i go to the section my entries are in and relate that to the categories i want to filter

{% set categoryListings = craft.entries({
  section: 'kelims',
  relatedTo: [
    { targetElement: category, field: 'filterThisCategory' }
  ]
}) %}

//if the entry has this category

{% if categoryListings|length %}

  display some html block

{% endif %}
{% endfor %}
3
  • I'm not sure I understand how you set the entry type in the kelims section. Could you tell me more about your filterThisCategory field? A screenshot of the field settings would help. I'm also unsure I understood correctly what you try to achieve. You just want to output some HTML if the entry you're currently viewing has a specific category, right?
    – nstCactus
    Sep 14 '20 at 16:58
  • My approach above was a wrong one. Regarding your last question, @nstCactus, yes, thats what i mean. I eventually fount the solution, with the help of these pages: craftcms.com/docs/3.x/categories-fields.html#templating, craftcms.com/docs/3.x/categories.html#querying-categories {% if entry.myFieldHandle.id('48, 49, 50, 51').exists() %} do this {% else %} do this {% endif %} myFieldHandle is the fieldHandle of the Category Group, where the categories i am searching for, are in.
    – Henrik
    Sep 19 '20 at 20:30
  • @nstCactus, so your hint with the "exists()" was the right one, but i needed to add the ids.
    – Henrik
    Sep 19 '20 at 20:35
1

craft.entries() returns an EntryQuery. You must then execute the query with one of those methods:

  • one()
  • all()
  • count()
  • exists()

In your case, I think .exists() is the best choice: {% if categoryListings.exists() %}

Edit: You may also have to execute your category query with {% for category in craft.categories().group('catGroup1').all() %}. See https://craftcms.com/docs/3.x/categories.html#querying-categories.

1
  • i tried your answers and hints, but no luck. maybe my approach with the craft.entries() is not the right one.
    – Henrik
    Sep 11 '20 at 20:16

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.