Login

WordWrap template tag

Author:
Daeg
Posted:
March 26, 2007
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

Basically a clone of the default "wrap" filter. I use it to generate plaintext e-mail that has to be broken at 75 characters.

{% wordwrap 80 %} Some text here, including other template tags, includes, etc. {% endwordwrap %}

I prefer this over the {% filter wordwrap:80 %} as my template (e-mail) writers keep screwing it up.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django import template
from django.utils.text import wrap

register = template.Library()

def wordwrap(parser, token):
	"""
	{% wordwrap 80 %}
	some really long text here, including other template functions, etc
	{% endwordwrap %}
	"""
	try:
		tag_name, len = token.split_contents()
	except ValueError:
		raise template.TemplateSyntaxError, "wordwrap tag requires exactly one argument"
	nodelist = parser.parse(('endwordwrap',))
	parser.delete_first_token()
	return WordWrapNode(nodelist, len)
wordwrap = register.tag(wordwrap)

class WordWrapNode(template.Node):
	def __init__(self, nodelist, len):
		self.nodelist = nodelist
		self.len = len
	
	def render(self, context):
		return wrap(str(self.nodelist.render(context)), int(self.len))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.