Django学习笔记 自定义标签
2016-01-20 14:57
645 查看
需求:
想在Template里根据一个Object的类名来分别做不同的操作。难点是如何获得类名。
解决方法
使用自定义标签。
1.在导入的APP下添加标签文件
2.getclassname.py 代码如下
3.然后在模板文件里可以使用
有时候可能会发生Load错误,需要重启下服务器,将新的Tag文件读取进来。
参考:
http://stackoverflow.com/questions/4060907/get-django-model-class-name-into-a-field
http://stackoverflow.com/questions/5427809/django-template-object-type
想在Template里根据一个Object的类名来分别做不同的操作。难点是如何获得类名。
解决方法
使用自定义标签。
1.在导入的APP下添加标签文件
app/ templatetags/ __init__.py getclassname.py
2.getclassname.py 代码如下
from django import template register = template.Library() @register.filter(name='get_class') def get_class(value): return value.__class__.__name__
3.然后在模板文件里可以使用
{% load getclassname %} {% if Object|get_class == 'AClassName' %} do something {% endif %}
有时候可能会发生Load错误,需要重启下服务器,将新的Tag文件读取进来。
有参数,返回值作为变量来使用时,如下。
想要获取到select的choices时如下---tag.py--- @register.filter(name='display_choices_value') def display_choices_value(bf,arg): """Returns the display value of a BoundField""" return dict(bf.field.choices).get(arg) ---template.html--- {{ field|display_choices_value:1 }} ---template.html--- {% with obj|mymethod:obj2 as newobj %} {% endwith %}
参考:
http://stackoverflow.com/questions/4060907/get-django-model-class-name-into-a-field
http://stackoverflow.com/questions/5427809/django-template-object-type
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 设计模式之行为型模式 - 调用行为的传递问题
- Python将excel导入到mysql中
- [div+css]晒晒最新制作专题推广页模板
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例