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. linebreaksli template filter by rokclimb15 6 years ago
  2. Convert newlines into <p> and </p> tags by jheasly 6 years, 2 months ago
  3. Template filter that divides a list into exact columns by davmuz 1 year, 5 months ago
  4. Soft-wrap long lines by Ubercore 5 years, 2 months ago
  5. Auto HTML Linebreak filter by punteney 5 years, 2 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?)