参考文章:
http://xiao80xiao.iteye.com/blog/519394 (django 自定义标签和过滤器)
http://www.cnblogs.com/btchenguang/archive/2012/09/05/2672364.html#WizKMOutline_1346841868165594 (Django框架学习-Templates进阶用法--下)
自定义标签放在app/templatetags下。下面是3个例子。
自定义标签1(过滤器):
vim test_tags.py
from django.template import Library register = Library() @register.filter(‘percent_decimal‘) def percent_decimal(value): value = float(str(value)) value = round(value, 3) value = value * 100 return str(value) + ‘%‘ #register.filter(‘percent_decimal‘, percent_decimal)
作用是将传过来的小数转换成百分比显示
views.py
def test(request): return render_to_response(‘test.html‘)
test.html
{% load test_tags %} {{ 12.09|percent_decimal}}
前端显示:
自定义标签2:
vim mytag.py
from django import template register = template.Library() @register.tag(name=‘mytag‘) def do_parse(parser,token): try: tag_name,format_string = token.split_contents() except: raise template.TemplateSyntaxError("tag error!") return Mytag(format_string[1:-1]) class Mytag(template.Node): def __init__(self, format_string): self.format_string = format_string def render(self, context): return self.format_string
views.py
def test2(request): return render_to_response(‘test2.html‘)
test2.html
<html> <body> {% load mytag %} {% mytag ‘excellent!‘ %} </body> </html>
前端显示:
自定义标签3:
vim currenttime_tag.py
from django import template import datetime register = template.Library() class CurrentTimeNode(template.Node): def __init__(self, format_string): self.format_string = str(format_string) def render(self, context): now = datetime.datetime.now() return now.strftime(self.format_string) def do_current_time(parser, token): try: tag_name,format_string = token.split_contents() except ValueError: msg = ‘%r tag requires a single argument‘ % token.split_contents()[0] raise template.TemplateSyntaxError(msg) return CurrentTimeNode(format_string[1:-1]) register.tag(‘current_time‘, do_current_time)
views.py
def test3(request): return render_to_response(‘test3.html‘)
test3.html
<html> <body> {% load currenttime_tag %} {% current_time "%Y-%m-%d %I:%M %p" %} </body> </html>
前端显示:
时间: 2024-10-23 06:38:19