Django 自定义模版标签
概要:
虽然Django已经提供能足够多的标签,但是有时候这些标签并不能很方便的实现我们的需求,所以Django为我们提供了自定义的机制,可以通过使用Python代码,自定义标签和过滤器来扩展模板引擎,然后使用{% load %}标签来加载自定义的模板标签。
自定义模板标签:
模板标签只有与某一个应用绑定时才会有意义,所以应该在对应的应用目录下创建对应的自定义标签python代码,需要注意的是Django规定:自定义模板标签必须在一个名称为templatetags的包中,所以自定义标签必须在templatetags这个目录中,而且templatetags这个目录中应该有一个__init__.py文件(即为一个python包)。标准的目录结构应该为:
│
├─myapp
│ │ admin.py
│ │ apps.py
│ │ forms.py
│ │ models.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ │
│ ├─templates
│ │ content_template.html
│ │ error.html
│ │ index.html
│ │ login.html
│ │ register.html
│ │ run_img_list.html
│ │ test.html
│ │ user_info.html
│ │
│ ├─templatetags
│ │ │ template_test.py
│ │ │ __init__.py
│ │ │
│ │ └─__pycache__
│ │ template_test.cpython-36.pyc
│ │ __init__.cpython-36.pyc
│ │
这里只做了一个简单的自定义标签,判断作者的名字是否为hwy,如果是则返回up主,否则返回真实作者名。
# -*- coding: utf-8 -*-
# @File : template_test.py.py
# @Author: 一稚杨
# @Date : 2018/8/12/012
# @Desc :
from django import template
from myapp.models import Article
register = template.Library()
@register.simple_tag
def test(pk):
author = Article.objects.get(pk=pk).author
if author == 'hwy':
author = 'up主'
return author
前端页面使用自定义标签:
使用方法较简单,只需要使用{% load 自定义标签名 %}来引入标签后使用{% 对应的方法名 需要传递的参数 %}方法来调用相应的方法即可得到相应的返回值。
代码:
</div>
{% for blog in data %}
<a style="" href="/content/?pk={{ blog.pk }}">{{ blog.title }}(阅读数量:{{ blog.readnum }})</a>
{% load template_test %}
<span id="hwy" onclick="change_like()" style="cursor: pointer">点赞:<span class="glyphicon glyphicon-thumbs-up active" ></span></span> 作者:{% test blog.pk %}
<br/>
{% endfor %}
</div>
最终效果:

https://zhuanlan.zhihu.com/p/42239302

被折叠的 条评论
为什么被折叠?



