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 %}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章