1

I'm building a knowledgebase for a client. The client has asked for content to be restricted by category and then by user. This part is easy enough - the users now use the same category field as articles. However, the templating is proving troublesome.

Currently I'm querying for the category IDs, building an array and using it in the main category query.

{% set searchQuery %}[{% for category in currentUser.kb__category %}{{ category.id }}{% if not loop.last %}, {% endif %}{% endfor %}]{% endset %}

This returns, for example, [268, 270, 273, 276]

Consistently, the page is displaying all but the first category. This happens no matter what the first assigned category is.

{% for category in craft.categories
  .group('knowledgeBase')
  .id(searchQuery)
  .level(1)
  .all()
%}

If I replace searchQuery with [268, 270, 273, 276] it works perfectly, which is baffling me as that's what has been output.

1

If it works hard-coded, try trimming your variable:

set searchQuery = searchQuery|trim

OR, even better, build an array:

{% set categories = [] %}

{% for category in currentUser.kb__category %}
   {% set categories = categories|merge(category.id) %}
{% endfor %}


{% for category in craft.categories
  .group('knowledgeBase')
  .id(categories)
  .level(1)
  .all()
%}
  • Sadly, neither of those worked. Building the array just results in an error trying to use merge when it return a string. – Christopher Dowson Jul 22 at 9:57

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.