More flexible "Partial Template"

 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. "Partial Templates" - an alternative to "include" by vigrid 5 years, 2 months ago
  2. split_contents2 for template tags by bl4th3rsk1t3 4 years, 10 months ago
  3. Partial templates, combine with and include by koblas 4 years ago
  4. partial tag by bl4th3rsk1t3 4 years, 10 months ago
  5. in_group template filter by whiteinge 5 years, 9 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?

#

(Forgotten your password?)