用法
{% alias my_url %}{% url music "rock","112" %}{% endalias %}
{{ my_url }} {{ my_url }} {{ my_url }}
python 代码
- from django import template
-
- register = template.Library()
-
- @register.tag
- def alias(parser, token):
- nodelist = parser.parse(('endalias',))
- parser.delete_first_token()
- return Alias(nodelist,token.contents.split()[1])
-
- class Alias(template.Node):
- def __init__(self,nodelist,alias):
- self.nodelist = nodelist
- self.alias = alias
-
- def render(self, context):
- output=self.nodelist.render(context)
- context[self.alias]=output
- return output
配合上次我写的统计访问的东西,和以下这段代码可以这样使用
{% alias now_url %}{% url mytube %}{% endalias %}
{% page_analytic_visit now_url %}
python 代码
- from django import template
- from django.core.exceptions import ObjectDoesNotExist
-
- from utils.url_decorate.models import PageAnalytic
-
- register = template.Library()
-
- @register.simple_tag
- def page_analytic_visit(url):
- try:
- return PageAnalytic.objects.get(url=url).visit
- except ObjectDoesNotExist:
- return 0