Login

Split a string to a list and add to select options

Author:
xuqingkuang
Posted:
April 23, 2009
Language:
Python
Version:
1.0
Tags:
template filter split
Score:
1 (after 1 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. split filter by Ciantic 7 years, 12 months ago
  2. linebreaksli template filter by rokclimb15 7 years, 10 months ago
  3. SelectDateWidget by silent1mezzo 4 years, 4 months ago
  4. Type checking templatetag filters by marcorogers 5 years, 2 months ago
  5. Pagination/Filtering Alphabetically by zain 6 years, 1 month ago

Comments

Please login first before commenting.