Add a value to the context for easy access and for access from include templates.
NOTE: This tag is composed from Django ticket: http://code.djangoproject.com/ticket/1322
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 | # -*- 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])
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
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.
#
Please login first before commenting.