from django import template import re register template Library def bu

 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
from django import template
import re
register = template.Library()
def build_menu(parser, token):
"""
{% menu active_class %}
HTML HERE
{% endmenu %}
"""
try:
tag_name, active_class = token.split_contents()
nodelist = parser.parse(('endmenu',))
parser.delete_first_token()
except:
raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]
return MenuObject(active_class, nodelist)
class MenuObject(template.Node):
def __init__(self, active_class, nodelist):
self.active_class = active_class
self.nodelist = nodelist
def render(self, context):
content = self.nodelist.render(context)
try:
current_path = template.resolve_variable('request.path', context)
except:
current_path = '/'
anchor = re.findall('<a.+?href=[\'|"](.+?)[\'|"].*?>', content)
while True:
if current_path in anchor:
break
else:
current_path = current_path.split('/')
current_path = current_path[:-2]
current_path.append('')
current_path = '/'.join(current_path)
content = re.sub('href=[\'|"]%s[\'|"]' % current_path, 'href="%s" class="%s"' % (current_path, self.active_class), content)
return content
register.tag('menu', build_menu)