make an unordered html list

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django import template
import re
register = template.Library()
@register.filter(name='html_list')
def make_html_list(value):
	"""Break a string down based on newline characters and for each line, enclose it in the <li> and </li> without the <ul> and </ul> tags. 
           Similar to the unordered_list filter but not requiring a list"""
	value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
	paras = re.split('\n', value)
	paras = ['<li>%s</li>' % p.strip().replace('\n', '<br/>') for p in paras]
	return '\n\n'.join(paras)

More like this

  1. Template filter that divides a list into exact columns by davmuz 2 weeks, 6 days ago
  2. Generic CSV Export by zbyte64 3 years, 8 months ago
  3. linebreaksli template filter by rokclimb15 4 years, 7 months ago
  4. Form splitting/Fieldset templatetag by peritus 3 years, 5 months ago
  5. dict recurse template tag for django by stefanp 1 year, 10 months ago

Comments

homunq (on November 2, 2011):
import re

from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

register = template.Library()

def needs_autoescape_register(filter):
    filter = register.filter(filter) # for >1.3.1:  ...., needs_autoescape=True)
    filter.needs_autoescape = True
    return filter

@needs_autoescape_register
def html_list_items(value, autoescape=None):
    """Break a string down based on newline characters and for each line, enclose it in the <li> and </li> without the <ul> and </ul> tags. 
           Similar to the unordered_list filter but not requiring a list"""
    if autoescape:
        esc = conditional_escape
    else:
        esc = lambda x: x
    if value:
        value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
        paras = re.split('\n', value)
    else:
        paras = []

    paras = ['<li>%s</li>' % esc(p.strip()).replace('\\n', '<br/>') for p in paras]
    return mark_safe('\n\n'.join(paras))

#

(Forgotten your password?)