personal web log written by izabeera and dryobates

include templatetag template django

try include in django templates

by dryobates

If you have to share some of your power on templates with your users then you would like to secure your site from their mistakes, don’t you?

Sometimes in our Django projects, we have to give some of our users ability to edit templates almost directly. Some parts of page are included from templates prepared by them. If they insert nonexistent templatetag or make some other mistake, then the whole page is unaccessible.

The easiest method I find is to use modified try_include [1] templatetag. In original code the only error that is catch is TemplateDoesNotExist. I have changed it to any exception and added logging. When a users ask why he doesn’t see included block I check in sentry [2] (which gathers our error messages) and quickly say what is the problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 import logging

 from django import template

 log = logging.getLogger(__name__)
 register = template.Library()


 class IncludeNode(template.Node):
     def __init__(self, template_name):
         self.template_name = template_name

     def render(self, context):
         try:
             # Loading the template and rendering it
             included_template = template.loader.get_template(
                     self.template_name).render(context)
         except Exception:
             log.exception('Error in try_include: %s' % self.template_name)
             included_template = ''
         return included_template


 @register.tag
 def try_to_include(parser, token):
     """Usage: {% try_to_include "head.html" %}

     This will fail silently if the template doesn't exist. If it does, it will
     be rendered with the current context."""
     try:
         tag_name, template_name = token.split_contents()
     except ValueError:
         raise template.TemplateSyntaxError, \
             "%r tag requires a single argument" % token.contents.split()[0]

     return IncludeNode(template_name[1:-1])
[1]http://djangosnippets.org/snippets/2058
[2]http://sentry.readthedocs.org/en/latest/index.html
dryobates
dryobates
Jakub Stolarski. Software engineer. I work professionally as programmer since 2005. Speeding up software development with Test Driven Development, task automation and optimization for performance are things that focus my mind from my early career up to now. If you ask me for my religion: Python, Vim and FreeBSD are my trinity ;) Email: jakub@stolarscy.com

Archive

Tag cloud