Skip to content

Instantly share code, notes, and snippets.

@fellypeavelino
Forked from goreilly/macros.twig
Created July 3, 2016 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fellypeavelino/c7233127422112a8170f10d967ff37fe to your computer and use it in GitHub Desktop.
Save fellypeavelino/c7233127422112a8170f10d967ff37fe 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 %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment