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!

1 Answer 1

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!
    – supazu
    Feb 16, 2021 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.