2

I have a macro for form fields, including select:

{% macro select(name, options) %}
  <select name="{{ name }}">
    {% for key, value in options %}
      <option value="{{ key }}">{{ value }}</option>
    {% endfor %}
  </select>
{% endmacro %}

Which I call with: {{ macro.select('name', {'key': 'value'}) }}

This works well when I define the key and value, however, I want to populate it from my categories.

{% set categoriesQuery = craft.categories().group('categories').all() %}

How can I make {'key': 'value'} loop over results from categoriesQuery? Hope that makes sense!

3

To convert the results of an Element Query into a custom key/value array you can use the index filter to specify what you want to use as the keys. So for example if you want the category slugs to be the keys and the category titles to be the values you'd do it like this:

{% set indexedCats = craft.categories.all()|index('slug') %}
{{ macro.select('name', indexedCats }}

=================

output:

<select name="name">
    <option value="cat-slug-1">Cat Title 1</option>
    <option value="cat-slug-2">Cat Title 2</option>
</select>

Swap in 'title' if you want the key and value to both be the same.

1
  • Awesome! Never knew about |index() - thanks!
    – brynli64
    Feb 16 at 2:43

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.