ifcontains 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. Decorate Template Tag (In-Line include and extend with local context) by rhomber 3 years, 4 months ago
  2. Row-Level, URL-based permissions for FlatPages by bradmontgomery 3 years, 11 months ago
  3. ifinlist template tag by nomadjourney 4 years, 4 months ago
  4. Url filter middleware by limodou 6 years, 2 months ago
  5. Additional Change List Columns by sansmojo 5 years, 10 months ago

Comments

nomadjourney (on February 17, 2009):

Check this out... it is a template filter-based solution:

http://www.djangosnippets.org/snippets/379/

#

(Forgotten your password?)