Skip to content

Instantly share code, notes, and snippets.

@goreilly
Created May 19, 2015 15:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save goreilly/5756bc2b5ef1ef8e33e3 to your computer and use it in GitHub Desktop.
Save goreilly/5756bc2b5ef1ef8e33e3 to your computer and use it in GitHub Desktop.
Twig HTML Select Macro with optgroups
{% macro select (name, id, options, selected, required, includeBlank) %}
<select name="{{ name }}" id="{{ id }}" {{ required ? 'required' : '' }}>
{% if includeBlank %}
<option value=""></option>
{% endif %}
{% for key, value in options %}
{% if value is iterable %}
<optgroup label="{{ key }}">
{% for subKey, subValue in value %}
<option value="{{ subKey }}" {{ subKey == selected ? 'selected' : '' }}>{{ subValue }}</option>
{% endfor %}
</optgroup>
{% else %}
<option value="{{ key }}" {{ key == selected ? 'selected' : '' }}>{{ value }}</option>
{% endif %}
{% endfor %}
</select>
{% endmacro %}
@goreilly
Copy link
Author

{% set groups = {
    'Optgroup A': {
        'A': 'Super Super',
        'B': 'Super',
        'C': 'Power',
        'D': 'Regular',
        'E': 'Guest'
    },
    'Optgroup B': {
        'ASDF': 'Super Admin',
        'ZXCV': 'Power User',
        'QWER': 'ZXCV 123'
    }
} %}
{{ macros.select('group', 'group', groups, user.group, true, true) }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment