Login

Partial Tag

Author:
mnbayazit
Posted:
July 11, 2010
Language:
Python
Version:
1.2
Tags:
context partial include ssi
Score:
-1 (after 1 ratings)

Lets you include another template and pass in named variables. Use like:

{% partial field_template field=form.city %}

If no key is specified, it will use "item" instead. You may pass in multiple variables as comma-separated key=value pairs.

 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
from django import template
from django.template import Library, Node, Variable, loader
from django.template.context import Context

register = template.Library()

def trim(s):
    return s.strip()

def stripquotes(s):
    if s[0] == s[-1] and s[0] in ('"',"'"):
        return s[1:-1]
    return s

class PartialTemplateNode(Node):
    def __init__(self, template_name, context_vars):
        self.template_name = template_name
        self.context_vars = dict(zip(context_vars.keys(),
            map(Variable, context_vars.values())))

    def render(self, context):
        template = loader.get_template(self.template_name)
        return template.render(Context(dict(zip(self.context_vars.keys(),
            map(lambda v: v.resolve(context), self.context_vars.values())))))

@register.tag(name='partial')
def partial_template(parser, token):
    bits = token.split_contents()
    tag, template, rest = bits[0], trim(stripquotes(bits[1])), ''.join(bits[2:])
    pairs = rest.split(',')
    context_vars = {}
    for pair in pairs:
        x = map(stripquotes, map(trim, pair.split('=')))
        if len(x) == 1:
            context_vars['item'] = x[0]
        else:
            context_vars[x[0]] = x[1]
    return PartialTemplateNode(template, context_vars)

More like this

  1. Partial templates, combine with and include by koblas 4 years, 10 months ago
  2. "Partial Templates" - an alternative to "include" by vigrid 6 years, 1 month ago
  3. More flexible "Partial Template" by robertrv 6 years ago
  4. CallTag - Just like include, but can pass parameters to it by limodou 8 years ago
  5. partial tag by bl4th3rsk1t3 5 years, 9 months ago

Comments

Please login first before commenting.