Login

Line & paragraph chopping

Author:
ludvig.ericson
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Score:
2 (after 2 ratings)

I was faced with the fact that I wanted to post 2 paragraph-long summaries on one of my sites, and this is what I did (you could of course cut it down earlier, but I'd say this belongs to what is called "template logic")

Use like so:

{% load myExtraModule %}
{{ blogpost.content|paragraphs:"2" }}

The lines filter works the exact same way, and you might want to improve on these a bit, I don't maintain them as I don't use them anymore.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.template import Library

register = Library()

@register.filter
def paragraphs(var, arg):
    paras = var.replace("\r\n", "\n").split("\n\n")
    return "\n\n".join(paras[:int(arg)])

@register.filter
def lines(var, arg):
    lines = var.replace("\r\n", "\n").split("\n")
    return "\n".join(lines[:int(arg)])

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.