funkybob / django-sniplates

Template snippet libraries for Django
MIT License
57 stars 18 forks source link

[WIP] Hacking out support for optgroup choices values. #31

Closed kezabelle closed 9 years ago

kezabelle commented 9 years ago

Given a choices of (from the docs):

MEDIA_CHOICES = (
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
)

the existing implementation doesn't do the same as Django's Select widget. This is me hacking out support for handling that use case.

WIP because:

the new wrapper object should be backwards compatible with the old choices format I think, but thoughts and feedback would be appreciated.

schinckel commented 9 years ago

Oh, my handling of optgroups is horrendous. Let me find a snippet.

schinckel commented 9 years ago

Something like:

{% block options %}
  {% for option_value, option_label in choices %}
    {# Handle optgroups #}
    {% if option_label.0|length > 1 %}
      <optgroup label="{{ option_value }}">
        {% for opt_value, opt_label, attrs in option_label %}
          {% widget 'form:option' option_label=opt_label option_value=opt_value %}
        {% endfor %}
      </optgroup>
    {% elif option_template %}
      {% widget option_template %}
    {% else %}
      {% widget 'form:option' %}
    {% endif %}
  {% endfor %}
{% endblock %}

{% block select %}
  <span class="uk-select-wrapper">
    <select {% widget 'form:attrs' %}>
      {% if widget.choices %}
        {% widget 'form:options' choices=widget.choices %}
      {% else %}
        {% widget 'form:options' %}
      {% endif %}
    </select>
  </span>
{% endblock %}

{% block option %}
  <option value="{{ option_value }}"
    {% if value == option_value|stringformat:'s' %}selected{% endif %}
    {% if multiple and option_value|stringformat:'s' in value %}selected{% endif %}
    {% if option_value.seconds != None %}data-seconds={{ option_value.seconds }}{% endif %}

    {% if attrs %}
      {% for k, v in attrs.items %}{{ k }}={{ v }} {% endfor %}
    {% endif %}
  >
    {{ option_label }}
  </option>
{% endblock %}