本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Django自定义模板标签和过滤器(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、创建模板库
在某个APP所在目录下新建包templatetags,然后在其中创建存储标签或者过滤器的的模块,名称随意,例如myfilters.py。
在这个模块中编写相关代码。
注意:templatetags所在APP应该在配置文件中进行配置。
2.定义过滤器
过滤器是一个函数,第一个参数是被处理的值,之后,可以有任意个参数,作为过滤器参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django import template
from django.template.defaultfilters import stringfilter
register=template.Library()
# 去除指定字符串
@register.filter(name= 'mycut' )
@stringfilter
def mycut(value,arg):
return value.replace(arg, '' )
# 注册过滤器
# register.filter(name= 'mycut' ,filter_func=mycut)
|
3.定义标签
simple_tag
处理数据,并返回具体数据
1 2 3 | @register.simple_tag(name= 'posts_count' )
def total_posts():
return Post.published. count ()
|
inclusion_tag
处理数据,并返回一个渲染的模板
1 2 3 4 5 6 | @register.inclusion_tag( 'blog/post/latest.html' )
def show_latest_posts( count =5):
latest_posts=Post.published.order_by( '-publish' )[:5]
return {
'latest_posts' :latest_posts,
}
|
blog/post/latest.html内容如下:
1 2 3 4 5 6 7 8 | <strong>最新文章</strong>
<ul>
{% for post in latest_posts %}
<li>
<a href= "{% url 'blog:post_detail' post_id=post.id %}" >{{ post.title }}</a>
</li>
{% endfor %}
</ul>
|
4.使用
使用自定义的标签或过滤器之前,在模板文件中,需要使用 {% load 模块名称 %}
加载自定义的标签和过滤器。
之后,就可以向使用Django自带的标签一样使用了。
注意:即使当前模板继承的基模板中已经load了自定义标签或过滤器所在的模块,在当前模板中,依然需要再次load。
【相关推荐:python视频教程】
以上就是Django自定义模板标签和过滤器(代码示例)的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
浅谈Python中的排序
Python3.7怎么运行
Python如何识别图片中的文字
Python如何传递参数
Python int函数怎么用
c语言和Python之间有什么区别
Python基础_文件操作实现全文或单行替换的方法
聊聊 Python 的双向队列
水仙花数如何用Python代码表示?
怎么安装Python的pygame库文件
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Django自定义模板标签和过滤器(代码示例)