zoukankan      html  css  js  c++  java
  • django自定义标签tag

    自定义标签:
    1.编写编译函数
    例如:
    {% current_time "%Y-%m-%d %I:%M %P" %}
    编译函数如下:
    from django import template
    def do_current_time(parser,token):
     try:
      tag_name,format_string=token.split_contents()
     except :
      raise template.TemplateSyntaxError ("tag requires a single argument ")
     if not(format_string[0]==format_string[-1] and format_string[0] in ('"',"'")):
      raise template.TemplateSyntaxError("%r tag's argument should be in quotes")%tag_name
     return CurrentTimeNode(format_string[1:-1])

    token.contents是一个字符串,这里是“current_time "%Y-%m-%d %I:%M %P"”
    token.split_contents()方法将参数按照空格分隔,但是不会将引号中的内容进行拆分。
    token.contents.split()会直接的分隔所有的空格,不够健壮。所以最好使用token.split_contents()方法。
    tag_name是标签的名字token.contents.split()[0]通常都会是你的标签的名字。就算没有参数。
    传递给CurrentTimeNode的参数为"%Y-%m-%d %I:%M %p" 。模板标签开头和结尾的引号使用 format_string[1:-1] 除去。
    模板标签编译函数 必须 返回一个 Node 子类,返回其它值都是错的。

    2.编写renderer(渲染器)
      编写一个Node的子类,包含一个render()方法。
    from django import template
    import datetime
    class CurrentTimeNode(template.Node)
     def __init__(self,format_string):
       self.format_string=format_string
     def render(self,context):
      return datetime.datetime.now().strftime(self.format_string)
    注意:
        render不能报异常。

    3.注册标签
    register.tag('current_time',do_current_time)
    需要两个参数:
    第一个就是模板标签的名字,第二个是编译函数。
    也可以使用@register.tag(name='current_time')

    完整例子:

    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
    #register.tag('mytag',do_parse)

    index.html

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
        <title></title>
    </head>
    <body>
    {% load mytag %}
    {% endfor %}
    {% mytag '陈建虹!' %}
    </body>
    </html>


    这里演示的都是tag最最基本的一些应用,深入的东西等到以后再分享吧。我也还没怎么用过,呵呵~~

  • 相关阅读:
    图解VS2008单元测试及查看代码覆盖率
    Effective C++:条款02:尽量以const, enum, inline替换#define (Prefer consts, enums, and inline to #defines.)
    Effective C++:条款01:视C++为一个语言联邦(View C++ as a federation of languages.)
    Effective C++:条款03:尽可能使用const (Use const whenever possible.)
    mysql foreign key <转>
    Linux下Apache绑定多个域名的方法 <转>
    python(1)input()和raw_input
    《精通CSS》读书笔记(1)
    CSS相对定位和绝对定位
    【分享】沪江网提供的每日一句API
  • 原文地址:https://www.cnblogs.com/chenjianhong/p/4145086.html
Copyright © 2011-2022 走看看