Login

ifcontains tag

Author:
dotbg
Posted:
February 16, 2009
Language:
Python
Version:
1.0
Tags:
tag if ifcontains block-tag
Score:
1 (after 1 ratings)

Django does not have ability to write {% if "item" in list %}, so I had to write this tag. It can be used just like ifequal tag

 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from django import template
from django.template import Variable, VariableDoesNotExist

register = template.Library()

class IfContainsNode(template.Node):
	def __init__(self, iterable_name, val, nodelist_true, nodelist_false, negate):
		self.iterable, self.val = Variable(iterable_name), val
		self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
		self.negate = negate
	
	def __repr__(self):
		return "<IfContainsNode>"
		
	def render(self, context):
		try:
			iterable = self.iterable.resolve(context)
		except VariableDoesNotExist:
			iterable = []
		
		if (self.negate and self.val in iterable) or \
			(not self.negate and self.val in iterable):
			return self.nodelist_true.render(context)
		return self.nodelist_false.render(context)


@register.tag
def ifcontains(parser, token):
	return do_ifcontains(parser, token, False)

@register.tag
def ifnotcontains(parser, token):
	return do_ifcontains(parser, token, True)

def do_ifcontains(parser, token, negate):
	bits = list(token.split_contents())
	if len(bits) != 3:
		raise template.TemplateSyntaxError, "%r takes two arguments" % bits[0]
	end_tag = 'end' + bits[0]
	nodelist_true = parser.parse(('else', end_tag))
	token = parser.next_token()
	if token.contents == 'else':
		nodelist_false = parser.parse((end_tag,))
		parser.delete_first_token()
	else:
		nodelist_false = template.NodeList()
	
	if not bits[2][0] == bits[2][-1] and bits[2][0] in ('"', "'"):
		raise template.TemplateSyntaxError, \
			"%r tag's third argument should be in quotes" % bits[0]

	return IfContainsNode(bits[1], bits[2][1:-1], nodelist_true, nodelist_false, negate)

More like this

  1. ifinlist template tag by nomadjourney 6 years, 3 months ago
  2. inclusion tag with template as variable by forgems 6 years, 2 months ago
  3. getting the related entries with a templatetag using django-tagging by V 6 years, 2 months ago
  4. Easy Conditional Template Tags by fragsworth 5 years, 10 months ago
  5. Template tag for stripping blank lines by akaihola 7 years, 2 months ago

Comments

Please login first before commenting.