Home  >  Article  >  Backend Development  >  Django custom template tags and filters (code example)

Django custom template tags and filters (code example)

不言
不言forward
2019-04-01 11:03:061954browse

This article brings you content about Django custom template tags and filters (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1, Create a template library

Create a new package templatetags in the directory where an APP is located, and then create a storage tag or filter in it Module with any name, such as myfilters.py.

Write relevant code in this module.

Note: The APP where templatetags is located should be configured in the configuration file.

2. Define the filter

The filter is a function. The first parameter is the value to be processed. After that, there can be any number of parameters as a filter. parameter.

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. Define tags

simple_tag

Process data and return specific data

@register.simple_tag(name='posts_count')
def total_posts():
    return Post.published.count()

inclusion_tag

Process the data and return a rendered template

@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.htmlThe content is as follows:

<strong>最新文章</strong>
<ul>
{% for post in latest_posts %}
<li>
    <a href="{% url &#39;blog:post_detail&#39; post_id=post.id %}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>

4. Use

Use Before customizing labels or filters, you need to use {% load module name%} to load custom labels and filters in the template file.

After that, you can use it just like using the tags that come with Django.

Note: Even if the module where the custom tag or filter is located has been loaded in the base template inherited by the current template, it still needs to be loaded again in the current template.

[Related recommendations: python video tutorial]

The above is the detailed content of Django custom template tags and filters (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete