Django自学笔记 3-2 模板语法概述

————总目录——前言——框架版本————

======================= 大爽歌作,made by big shuang =======================

二、模板语法介绍

参考:https://docs.djangoproject.com/en/2.2/topics/templates/#the-django-template-language

0 总介绍

官方文档介绍:

A Django template is simply a text document or a Python string
marked-up using the Django template language. Some constructs are
recognized and interpreted by the template engine. The main ones are
variables and tags.

A template is rendered with a context. Rendering replaces variables
with their values, which are looked up in the context, and executes
tags. Everything else is output as is.

The syntax of the Django template language involves four constructs: Variables,Tags,Filters,Comments

我的菜鸡翻译:
Django模板,只是使用Django模板语言标记的,文本文档或Python字符串。
模板引擎可以识别和解释某些结构(主要是变量和标记)。
模板使用context变量渲染:渲染时,替换掉模板的变量(使用context里面对应的值),并执行标记的模板代码(tags里的代码);其他则按原文输出。
Django模板语言的语法包含四种结构: Variables,Tags,Filters,Comments

补充:context变量:实际就是个字典对象

1 Variables(变量)

直接输出context里的变量
写法为:

{{ variable}}

2 Tags(标签)

在模板里实现随心所欲的逻辑。
这个解释很笼统,因为Tags的功能本身很笼统,
Tags能够实现任意的逻辑代码,既能输出变量,也能用作控制结构(if语句或for循环),还能从数据库中获取内容,甚至启用对其他模板标记的访问。

写法为:

{% tags %}

3 Filters(过滤器)

转换变量(Variables)和标签(Tags)参数的值(或者说呈现格式)。
举例如

{{ str_variable|title }}

其中|title就是过滤器,title 过滤器的作用是让str_variable里的单词首字母大写。

4 Comments(注释)

单行注释

{# this won't be rendered #}

多行注释

{% comment "Optional note" %}
    <p>This won't be rendered</p>
{% endcomment %}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章