Get the App
SLTechnology News&Howtos  ›  Development  › 

How to customize tag and filter of jinja2 by django

Shulou Source: shulou.com Published: 2022-06-02 11:22:21 09月11日 Update

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!

Tags: Content parameters file format article case template learning help function variable scene file name easy to understand more organization directory knowledge tape industry Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Huawei Redmi Apple Shulou Information