Login

Set Template Tag

Author:
Xin
Posted:
May 6, 2007
Language:
Python
Version:
.96
Score:
2 (after 6 ratings)

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

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

Comments

Archatas (on May 7, 2007):

Xin, check the "with" template tag which is integrated into the core of the latest revisions of django.

#

Xin (on May 7, 2007):

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.

#

Tomek (on December 23, 2010):

I like it. Useful.

#

Tomek (on December 23, 2010):

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.