Login

Split a string to a list and add to select options

Author:
xuqingkuang
Posted:
April 23, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

The template filter is use for split a string such as "foo|foobar|bar" to select option widget. You can define the splitter of the string by yourself.

Usage: Add the code into templatetags folder of a installed app, then add below code into your template file.

` {% load split_as_option %}

<select name="widget_name"> {{ QuerySet.values|split_as_option:"|" }} </select> `

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django import template
from django.utils.safestring import mark_safe, SafeData
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def split_as_option(value, splitter='|', autoescape=None):
    if not isinstance(value, SafeData):
        value = mark_safe(value)
    value = value.split(splitter)
    result = ""
    for v in value:
        result += '<option value="%s">%s</option>\n' % (v, v)
    return mark_safe(result)
split_as_option.is_safe = True
split_as_option.needs_autoescape = True

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.