在html模板里面加python函数(simple_tag与filter)

自定义函数
			simple_tag
				a. app下创建templatetags目录
				b. 任意xxoo.py文件
				c. 创建template对象 register
				d. 
					@register.simple_tag
					def func(a1,a2,a3....)
						return "asdfasd"
				e. settings中注册APP
				f. 顶部 {% load xxoo %}
				g. {% 函数名 arg1 arg2 %}
				缺点:
					不能作为if条件
				优点:
					参数任意
			filter
				a. app下创建templatetags目录
				b. 任意xxoo.py文件
				c. 创建template对象 register
				d. 
					@register.filter
					def func(a1,a2)
						return "asdfasd"
				e. settings中注册APP
				f. 顶部 {% load xxoo %}
				g. {{ 参数1|函数名:"参数二,参数三" }} {{ 参数1|函数名:数字 }}
				缺点:
					最多两个参数,不能加空格
				优点:
					能作为if条件

  《pyhton文件demo.py》

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def fun1(a1,a2,a3):
    return a1 + a2 +a3

@register.filter
def fun2(a1,a2):
    print(a2,type(a2))
    return a1 + str(a2)

  《html文件》

        {{ name }}
        {{ name|lower }}
      {% fun1 1 2 3 %}
      {{ '123'|fun2:'213' }}

  

posted @ 2018-05-06 00:36  梦中琴歌  阅读(598)  评论(0编辑  收藏  举报