Login

Set Template Tag

Author:
Xin
Posted:
May 6, 2007
Language:
Python
Version:
.96
Tags:
tag
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. extend tag with cache by fredd4 7 years, 3 months ago
  2. Updated - Template context debugger with (I)Pdb by dnordberg 5 years, 9 months ago
  3. "Partial Templates" - an alternative to "include" by vigrid 6 years, 3 months ago
  4. Django cycle tag that doesn't continue where it left off by wilfred 2 years, 4 months ago
  5. {% with %} template tag by SmileyChris 8 years, 2 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.