Login

make an unordered html list

Author:
techiegurl
Posted:
May 22, 2008
Language:
HTML/template
Version:
Not specified
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

  1. Bootstrap Accordian by Netplay4 5 years, 10 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 10 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 10 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 11 months ago
  5. Pagination Django with Boostrap by guilegarcia 9 years, 1 month 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))

#

Please login first before commenting.