Login

More flexible "Partial Template"

Author:
robertrv
Posted:
February 6, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This is an extension of the snippet http://www.djangosnippets.org/snippets/1302/ to make it a bit more flexible and been able pass more than one parameter to our "Partial Template". To use it you can

{% partial_template template_name param1:variable1 param2:variable2 ... %}

or:

{% partial_template partials/mini_template.html item:data1 var2:"False" var3:"2*2" %}

 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from django.template import Library, Node, loader, resolve_variable, \
    TemplateSyntaxError
from django.template.context import Context

register = Library()

class PartialTemplateNode(Node):
    """
        Partial template templatetag to pass simple parameters formatted like:
        
        {% partial_template template_name:template_name param1:variable1 param2:variable2 param4:"True" param5:22 %}
        
        Based on other two django snippets:
            http://www.djangosnippets.org/snippets/297/
            http://www.djangosnippets.org/snippets/1302/
    """
    def __init__(self, template_name, params):
        self.template_name = template_name
        self.params = params

    def render(self, context):

        for k,v in self.params.items():
            if v[0] == '\"' or v[0] == '\'':
                try:
                    # Trying to evaluate the python code in quotes (like "True")
                    self.params[k] = eval(v[1:-1])
                    continue
                except:
                    pass
            self.params[k] = resolve_variable(v, context)
        template = loader.get_template('%s' % (self.template_name,))
        template_context = Context(self.params)
        return template.render(template_context)

@register.tag
def partial_template(parser, token):
    items = token.split_contents()
    if len(items)<3:
        raise TemplateSyntaxError('Missing template tag arguments. '\
            'At least 2 arguments needed')
    
    template_name = items[1]
    
    parameters = {}
    
    for item in items[2:]:
        param, value = item.split(':')
        param = param.strip()
        value = value.strip()
        parameters[param] = value
        
    return PartialTemplateNode(template_name, parameters)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

buriy (on February 10, 2009):

templates are supposed to be safe. so don't use eval(v[1:-1])

second, why not add parent content to partial by default?

#

Please login first before commenting.