Login

make an unordered html list

Author:
techiegurl
Posted:
May 22, 2008
Language:
HTML/template
Version:
Not specified
Tags:
html list
Score:
0 (after 0 ratings)

This custom filter takes in a string and breaks it down by newline then makes each separate line an item in an unordered list. Note that it does not add the <ul> </ul> tags to give the user a chance to add attributes to the list. This is based of the 'linebreaks' filter built in django

 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

Comments

homunq (on November 2, 2011):
<pre>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)) </pre>

#

Please login first before commenting.