zoukankan      html  css  js  c++  java
  • 定制Django的Tag和Filter(一)

    1、在 app 目录下创建 templatetags 目录(目录名只能是 templatetags)。

    如:

    app/
        __init__.py
        models.py
        templatetags/
            __init__.py
            mytag.py
        views.py

    2、创建任意 .py 文件,如:mytag.py

    为了成为一个可用的标签库,这个模块必须包含一个名为 register的变量,它是template.Library 的一个实例,所有的标签和过滤器都是在其中注册的。所以把如下的内容放在你的模块的顶部:

    from django import template
    from django.utils.safestring import mark_safe
    register = template.Library()
    @register.filter
    def filter_multi(v1,v2):
        return  v1 * v2
    
    @register.simple_tag
    def simple_tag_multi(v1,v2):
        return  v1 * v2
    
    @register.simple_tag
    def my_input(id,arg):
        result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
        return mark_safe(result)

    3、在setting.py中添加'library'字典:
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR+'/templates'],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'my_tags':'RunoobDemo.templatetags.my_tags',
                }
            },
        },
    ]

    4.模板template 中的html中:

    {% load my_tags %}
    {{ 11|my_filter:22}}<br>
    {% my_tag1 11 22 33 %}
    
    ##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
  • 相关阅读:
    Leetcode---2. Add Two Numbers
    Leetcode---1. Two Sum
    dpkg:处理 xxx (--configure)时出错解决方案
    ubuntu 14.04搭建tensorflow-gpu开发环境
    Leetcode---35. Search Insert Position
    Leetcode---21. Merge Two Sorted Lists
    Leetcode----26. Remove Duplicates from Sorted Array
    Leetcode---28. Implement strStr()
    Leetcode----27 Remove Element
    qemu 安装 ubuntu-server 虚拟机
  • 原文地址:https://www.cnblogs.com/johnyang/p/13264416.html
Copyright © 2011-2022 走看看