# -*- coding: utf-8 -*-
from django import template
register = template.Library()
class SetVariable(template.Node):
def __init__(self,varname,value):
self.varname = varname
self.value = value
def render(self,context):
var = template.resolve_variable(self.value,context)
if var:
context[self.varname] = var
else:
context[self.varname] = context[self.value]
return ''
@register.tag(name='set')
def set_var(parser,token):
"""
Example:
{% set category_list category.categories.all %}
{% set dir_url "../" %}
{% set type_list "table" %}
{% include "category_list.html" %}
"""
from re import split
bits = split(r'\s+', token.contents, 2)
return SetVariable(bits[1],bits[2])
Comments
Xin, check the "with" template tag which is integrated into the core of the latest revisions of django.
#
Yes, but when I need more variables to set, with tag "with" I need to put two lines (with and endwith) for each variable, while with "set" I only need a one line.
#
I like it. Useful.
#
It is nice to set some variable in template and then use it anywhere bellow. Sometimes using with is arduous.
#