blog stats
seamusc.com

Break page template tag

Published on May 31, 2007

Just looking over some of the posts here I realised that many of them are very long. Django's template system will let you truncate a piece of text using the truncatewords:N tag but this often is not what you want.

For this site if i decide to truncate all my posts at say 200 words then it is possible that a <code> or <p> tag will be left open, which will mess up the appearance of the page.

It would be nicer if I could just tell the template system where to break my post so that bad things don't happen or that a post is broken with only a few words to go.

This little piece of code should implement this, breaking the page when it finds BREAKHERE on it's own on a line.

app/templatetags/breakhere.py

from django import template
import string

register = template.Library()


# register the templatetag
@register.filter("breakhere")
def breakhere(content, hide="True"):
    out = ''
    for line in string.split(content,"\n"):
        print repr(line)
        if line == 'BREAKHERE\r':
            if hide == "False":
                continue
            return out
        out += line
    return out


templates/app/foo.html

{% load breakhere %}

{% block content %}
{{ object.content|breakhere }}
{% endblock %}


When you don't want to break the page use {{ object.content|breakhere:"False" }}


Comments

David, biologeek
July 12, 2007 at 9:33 a.m.

Why don't you just try to split your content on BREAKHERE? Like that:


first_part, second_part = content.split('BREAKHERE')


with appropriated try...except of course.