https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
有一个应用polls结构如下,如何自定义templatetags
polls/
__init__.py
models.py
templatetags/
__init__.py
poll_extras.py
views.py
INSTALLED_APPS = [
.....
'polls'
]
在polls目录下新建一个templatetags目录,目录下创建一个空文件__init__.py以让python识别到其是一个包
from django import templateregister = template.Library()
@register.filter(name='cut')
def cut(value, arg):
return value.replace(arg, '')
@register.filter
def lower(value):
return value.lower()
开启takes_context,可以访问当前上下文context
import datetime
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def current_time(context, format_string):#context接收当前页面的上下文字典
timezone = context['timezone']
return your_get_current_time_method(timezone, format_string)
#results.html
<ul>
{% for choice in choices %}
<li> {{ choice }} </li>
{% endfor %}
</ul>
@register.inclusion_tag('results.html')
def show_results(poll):
choices = poll.choice_set.all()
return {'choices': choices}
{% show_results poll %} //返回如下
<ul>
<li>First choice</li>
<li>Second choice</li>
<li>Third choice</li>
</ul>
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。