Login

Line & paragraph chopping

Author:
ludvig.ericson
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Tags:
chop cut line paragraph block
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. Trim the center of a string by grillermo 2 years, 7 months ago
  2. filter for extracting a number of paragraphs from any HTML code by rafadev 4 years ago
  3. JSONField by deadwisdom 7 years, 10 months ago
  4. Log all interaction with user to the DB by inuwashi 4 years, 5 months ago
  5. Lorem Ipsum - Random content for your mockups by gfranxman 8 years, 4 months ago

Comments

Please login first before commenting.