How-to display a dropdown field with optgroups? The display of a dropdown without optgroups is defined:

{% set field = craft.app.fields.getFieldByHandle('&lt;FieldHandle&gt;') %}

&lt;select name="fields[&lt;FieldHandle&gt;]"&gt;
    {% for option in field.options %}

        {% set selected = entry is defined
            ? entry.&lt;FieldHandle&gt;.value == option.value
            : option.default %}

        &lt;option value="{{ option.value }}"
                {% if selected %}selected{% endif %}&gt;
            {{ option.label }}
        &lt;/option&gt;
    {% endfor %}
&lt;/select&gt;


The following error occurs:

Key "default" for array with keys "optgroup" does not exist.
This would work for both with or without optgroup (replace aDropdown with your fieldname):

{% set field = craft.app.fields.getFieldByHandle('aDropdown') %}

{# If we have optgroups in this field, set a counter to 0 else return false #}

{% set optgroupCount = field.optgroups ? 0 : false %}
&lt;select name="fields[aDropdown]"&gt;
    {% for option in field.options %}

        {% if option.optgroup is not defined %}
            {# This is a regular option #}
            {% set selected = entry is defined ? entry.aDropdown.value == option.value : option.default %}
            &lt;option value="{{ option.value }}" {% if selected %}selected{% endif %}&gt;
                {{ option.label }}
            &lt;/option&gt;
        {% else %}
            {# This is an optgroup #}
            {# Check if we should close a group before opening a new one.#}
            {{ optgroupCount &gt; 0 ? '&lt;/optgroup&gt;' }}
            &lt;optgroup label="{{ option.optgroup }}"&gt;
            {% set optgroupCount = optgroupCount + 1 %}
        {% endif %}

    {% endfor %}
    {# If we had optgroups better close the last one #}
    {{ optgroupCount ? '&lt;/optgroup&gt;' }}
&lt;/select&gt;