How do I access all page objects in django-cms from every page?

thomallen picture thomallen · Dec 7, 2010 · Viewed 7.6k times · Source

I am using Django CMS 2.1.0.beta3 and am encountering a problem. I need to have access to all the pages in a variable so that I can loop through them and create my navigation menu using a for loop. The show_menu functionality provided with django cms will not work for what I am doing.

I need a queryset with all pages so I can do something similar to the following:

{% for page in cms_pages %}
    {{ page.title }}
{% endfor %}    

Does anyone know how I can gain access to all the published page objects like that on ALL pages?

Answer

thomallen picture thomallen · Dec 10, 2010

I ended up solving this problem by creating a templatetag in django that serves up all of the cms pages:

app/template_tags/navigation_tags.py:

from django import template
from cms.models.pagemodel import Page

register = template.Library()

def cms_navigation():
    cms_pages = Page.objects.filter(in_navigation=True, published=True)
    return {'cms_pages': cms_pages}

register.inclusion_tag('main-navigation.html')(cms_navigation)

Then in the templates you call the template tag as follows:

{% load navigation_tags %} {% cms_navigation %}

This requires that you have a main-navigation.html file created. Here then the HTML from that template will be injected into the template wherever the tag is and the main-navigation.html will have access to whatever was passed to it in the custom tag function:

templates/main-navigation.html:

<ul id="navigation">
    {% for page in cms_pages %}
         {{ page.get_title }}
    {% endfor %}    
</ul>

I hope this helps someone better understand templatetags. I found the documentation a bit confusing on this subject.