Home Backend Development Python Tutorial Python的Django框架中自定义模版标签的示例

Python的Django框架中自定义模版标签的示例

Jun 10, 2016 pm 03:09 PM
django

为了自定义一个模板标签,你需要告诉Django当遇到你的标签时怎样进行这个过程。

当Django编译一个模板时,它将原始模板分成一个个 节点 。每个节点都是 django.template.Node 的一个实例,并且具备 render() 方法。 于是,一个已编译的模板就是 节点 对象的一个列表。 例如,看看这个模板:

Hello, {{ person.name }}.

{% ifequal name.birthday today %}
  Happy birthday!
{% else %}
  Be sure to come back on your birthday
  for a splendid surprise message.
{% endifequal %}

Copy after login

被编译的模板表现为节点列表的形式:

  •     文本节点: "Hello, "
  •     变量节点: person.name
  •     文本节点: ".\n\n"
  •     IfEqual节点: name.birthday和today

当你调用一个已编译模板的 render() 方法时,模板就会用给定的context来调用每个在它的节点列表上的所有节点的 render() 方法。 这些渲染的结果合并起来,形成了模板的输出。 因此,要自定义模板标签,你需要指明原始模板标签如何转换成节点(编译函数)和节点的render()方法完成的功能 。

在下面的章节中,我们将详细解说写一个自定义标签时的所有步骤。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check django version How to check django version Dec 01, 2023 pm 02:25 PM

How to check django version

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django vs. Flask: A comparative analysis of Python web frameworks

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django Framework Pros and Cons: Everything You Need to Know

How to check django version How to check django version Nov 30, 2023 pm 03:08 PM

How to check django version

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations

What is the difference between django versions? What is the difference between django versions? Nov 20, 2023 pm 04:33 PM

What is the difference between django versions?

Is django front-end or back-end? Is django front-end or back-end? Nov 21, 2023 pm 02:36 PM

Is django front-end or back-end?

How to install django How to install django Dec 19, 2023 am 11:38 AM

How to install django

See all articles