Simple Menu for Django Flatpages

Generate a menu dynamically from your Django flatpages using templatetags. Using Django as a simple CMS.

Create a folder called 'templatetags' in your app folder (I use an app called utils) and inside it create a file called flatpage_menu.py, put the follwing code inside:

from django.template import Library, Node
from django.contrib.flatpages.models import FlatPage
register = Library()

def flatpage_menu():
    # Create an unordered list of all flatpages
    pages = FlatPage.objects.all()
    menu = '<ul>'
    for i in range(len(pages)):
        menu += '<li>'+'<a href="'+pages[i].url+'" title="'+pages[i].title+'">'+pages[i].title+'</a></li>'
    menu += '</ul>'
    return menu 

register.simple_tag(flatpage_menu)

now add this to the top of your template to register the template tag:

{% load flatpage_menu %}

and finally where you want the menu to appear in your template place this:

{% flatpage_menu %}

You should now have a nice menu of all your flatpages.

Files

Simple Menu for Django Flatpages

Posted on July 29, 2007
Tags: Django, Python

Comments

1

giorgi commented, on August 21, 2007 at 7:24 p.m.:

nice hint - thanks ;)

2

areczek commented, on January 22, 2008 at 5:36 p.m.:

for page in pages:
menu += ...
would be simpler ;)

Post a comment

Your name:

Comment: