Skip to content

Instantly share code, notes, and snippets.

@mkoistinen
Last active May 26, 2016 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkoistinen/249043bee3c53dd826dcbb7e80c4288e to your computer and use it in GitHub Desktop.
Save mkoistinen/249043bee3c53dd826dcbb7e80c4288e to your computer and use it in GitHub Desktop.
templatetag to get a page object by its ID
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from classytags.arguments import Argument
from classytags.core import Options
from classytags.helpers import AsTag
from cms.utils import get_site_id
from cms.templatetags.cms_tags import _get_page_by_untyped_arg
register = template.Library()
class PageById(AsTag):
name = 'page_by_id'
options = Options(
Argument('page_id'),
Argument('site_id', required=False, default=None),
'as',
Argument('varname', required=True, resolve=False)
)
def get_value(self, context, page_id, site_id):
"""Returns the published page with the given page ID, or None."""
site_id = site_id or get_site_id(None)
request = context.get('request', None)
return _get_page_by_untyped_arg(page_id, request, site_id)
register.tag(PageById)
Make a directory in your project called "templatetags" (include an empty __init__.py inside)
Add the file below: home_tags.py
Use it like this:
````
{% load home_tags %}
{# You should be able to pass anything that page_url accepts here #}
{% page_by_id "about" as the_about_page %}
<h1>{{ the_about_page.creation_date }}</h1>
...
````
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment