Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize tag and filter of jinja2 by django

2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "django how to customize jinja2 tag and filter", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "django how to customize jinja2 tag and filter" this article.

Django uses jinja2 templates by default.

Jinja2 templates come with all kinds of filter and tag, and can also be customized.

Main format

{{variable}}

{{variable | filter:arg}}

{% tag%}

The official website http://jinja.pocoo.org/docs/2.10/

The customization process is as follows: 1. Create the fixed package name templatetags under the app directory, and create the py file

2. Mytags.py#/usr/bin/env python3from django import templateregister=template.Library () @ register.filter () def myfilter_name1 (XMagney): return x+y@register.filter () def myfilter_name2 (x): return x*x@register.simple_tag () def mytag_name1 (xMagy): return xonomy

Decorate filter with @ register.filter ()

Decorate tag with @ register.simple_tag ()

Note that service loading needs to be restarted

3. Html file {% load mytags%} Title case filterori: {{n}} {{n | myfilter_name1:5}} {{n | myfilter_name2}} case simple tag {% mytag_name1 3 5%}

The first line {% load mytags%}, that is, the file name of load py, can be used directly by tag

Filter format {{variable | filter: parameter}}

Simpletag format {% tag parameter%}

Functionally, some of the same operations can be achieved.

Some scenarios filter is better to use, such as {% if n | filter > 10%}

4. Page

The above is all the content of the article "how django customizes jinja2's tag and filter". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report