# 一、模板 ## 1.1 概述 `Django`中的模板是指可以动态生成任何基于文本格式文件的技术(如`HTML`、`CSS`等)。 `Django`中内置了自己的模板系统,称为`DTL(Django Template Language),Django模板语言`。 ## 1.2 配置 `settings.py`中关于模板的配置如下: ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 指定模板文件存储的位置 'DIRS': [ BASE_DIR , 'templates'], # 自动搜索应用目录 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` ## 1.3 渲染模板 在`Django`的模板系统中,可通过`render()`函数来完成渲染模板的功能。 其语法结构是: ```python from django.shortcuts import render render(request,template_name,content=None,content_type=None,status=None) ``` - `request`代表用于生成此响应的请求对象 - `template_name`代表要渲染的模板文件的名称 - `content`代表要传递到模板的数据形成的数据**字典** - `content_type`代表模板文件的`MIME`类型,默认为`text/html` - `status`代表响应的状态码,默认为`200` > `render()`函数返回`HttpResponse`对象,是更加简洁的输出。 # 二、DTL `DTL`中的语法涉及四个部分: - 注释 -- 注释 - 变量 -- 变量在模板被执行时将被替换为实际值 -- {{ ... }} - 标签 -- 用于控制模板逻辑 {% ... %} - 过滤器 -- 用于转换变量或标签的值 ## 2.1 变量 在`DTL`中的变量通过双花括号进行访问: ```python {{ variable}} {{ variable.key }} {{ variable.index }} {{ variable.property }} ``` `views.py`的代码如下: ```python def variable(request): username = 'Tom' age = 23 sex = True score = { 'chinese':128, 'math':149, 'english':122 } friends = ['John','Rose','Frank','Ben'] return render(request,'variable.html',locals()) ``` `variable.html`的代码如下: ```html Variable username:{{ username }} age:{{ age }} sex:{{ sex }} chinese:{{ score.chinese }} math:{{ score.math }} english:{{ score.english }} {{ friends.0 }},{{ friends.1 }},{{ friends.2 }},{{ friends.3 }} ``` ## 2.2 标签 ### 2.2.1 `for` `for`标签用于遍历列表或字典,语法结构是: ```html {% for iterate_value in sequence %} ... ... {% endfor %} {% for iterate_value in sequence %} ... ... {% empty%} ... ... {% endfor %} ``` `for`循环中内置了一组变量供用户使用: | 变量 | 描述 | | --------------------- | -------------------------------------- | | `forloop.counter` | 循环记数器,从1开始 | | `forloop.counter0` | 循环记数器,从0开始 | | `forloop.revcounter` | 反向循环记数器,最后一个为1 | | `forloop.revcounter0` | 反向循环记数器,最后一个为0 | | `forloop.first` | 当前循环为第一个时,该变量值为`True` | | `forloop.last` | 当前循环为最后一个时,该变量值为`True` | `views.py`的代码如下: ```python def forloop(request): books = [ { 'bookname': '孙子兵法大全集(超值金版)', 'price': 18.4, 'publishing': '新世界出版社', 'category': '历史' }, { 'bookname': '甲骨文丛书·拿破仑大帝(全2册) ', 'price': 119.5, 'publishing': '中信出版集团', 'category': '传记' }, { 'bookname': 'JavaScript DOM编程艺术(第2版)', 'price': 42.70, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': '精通iOS开发 第8版', 'price': 102.20, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': 'UNIX网络编程 卷1 套接字联网API(第3版)', 'price': 102.9, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': '曾国藩的正面与侧面:1+2(套装共两册)', 'price': 59.30, 'publishing': '岳麓书社', 'category': '传记' }, { 'bookname': '普京传:不可替代的俄罗斯硬汉 [Mr.Putin: Operative In The Kremlin] ', 'price': 39, 'publishing': '红旗出版社', 'category': '传记' }, ] context = { 'books':books } return render(request,'forloop.html',context) ``` `forloop.html`的代码如下: ```html 序号 书名 价格 出版社 分类 {% for book in books %} {{ forloop.counter }} {{ book.bookname }} {{ book.price }} {{ book.publishing }} {{ book.category }} {% endfor %} ``` ### 2.2.2 `cycle` 在每次遇到`cycle`标记时,都会产生一个参数。第一次产生第一个参数,第二次产生第二个参数,依次类推。一旦用尽所有参数,再次循环时则产生第一个参数。其语法结构是: ```html {% cycle 'value1' 'value2' 'value3' '...'%} ``` ### 2.2.3 `if` ```html {% if condition %} ... {% endif %} 或者 {% if condition %} ... {% else %} ... {% endif %} 或者 {% if condition %} ... {% elif condition %} ... {% elif condition %} ... {% else %} ... {% endif %} ``` ### 2.2.4 `templatetag` 基本语法结构是: ```html {% templatetag templatebit%} ``` | 模板位(`templatebit`) | 说明 | | --------------------- | ---- | | `openblock` | `{%` | | `closeblock` | `%}` | | `openvariable` | `{{` | | `closevariable` | `}}` | | `opencomment` | `{#` | | `closecomment` | `#}` | ### 2.2.5 `verbatim` `verbatim`标签用于告诉`DTL`停止渲染此标签内的内容,其语法是: ```html {% verbatim%} ... {% endverbatim %} ``` ### 2.2.6 `url` `url`标签用于近回与指定路由和可选参数相匹配的绝对路径引用(不包括域名),其格式为: ```html {% url 'route_name' arg1 arg2 .. %} ``` ### 2.2.7 `include` `include`标签用于在一个模板文件中包含另外一个模板文件,其语法结构是: ```html {% include 'filename' %} ``` ### 2.2.8 `csrf_token` `csrf_token`称为令牌标签,其作用是为了防止跨域请求伪造,其原理是表单内添加一个隐藏域,其值为加密信息,在表单`POST`提交时将与服务器产生的加密信息进行匹配,匹配成功则意味合法用户。 ```html {% csrf_token %} ``` ## 2.3 过滤器 过滤器用于转换变量或标签参数的值,其语法结构是: ```html {{ value | filter}} ``` ### 2.3.1 `safe` `safe`用于标记一个字符串在输出前不需要对`HTML`标记进行转义,语法结构是: ```html {{ value | safe }} ``` ### 2.3.2 `truncatechars` 用于完成字符串的截取,其语法结构是: ```html {{ value | truncatechars:长度 }} ``` ### 2.3.3 `yesno` 将`True`,`False`和`None`(可选)值映射到以英文逗号分隔的数据,其结构为: ```html {{ value | yesno:"True时的值,False时的值,None时的值"}} ``` Loading... # 一、模板 ## 1.1 概述 `Django`中的模板是指可以动态生成任何基于文本格式文件的技术(如`HTML`、`CSS`等)。 `Django`中内置了自己的模板系统,称为`DTL(Django Template Language),Django模板语言`。 ## 1.2 配置 `settings.py`中关于模板的配置如下: ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 指定模板文件存储的位置 'DIRS': [ BASE_DIR , 'templates'], # 自动搜索应用目录 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` ## 1.3 渲染模板 在`Django`的模板系统中,可通过`render()`函数来完成渲染模板的功能。 其语法结构是: ```python from django.shortcuts import render render(request,template_name,content=None,content_type=None,status=None) ``` - `request`代表用于生成此响应的请求对象 - `template_name`代表要渲染的模板文件的名称 - `content`代表要传递到模板的数据形成的数据**字典** - `content_type`代表模板文件的`MIME`类型,默认为`text/html` - `status`代表响应的状态码,默认为`200` > `render()`函数返回`HttpResponse`对象,是更加简洁的输出。 # 二、DTL `DTL`中的语法涉及四个部分: - 注释 -- 注释 - 变量 -- 变量在模板被执行时将被替换为实际值 -- {{ ... }} - 标签 -- 用于控制模板逻辑 {% ... %} - 过滤器 -- 用于转换变量或标签的值 ## 2.1 变量 在`DTL`中的变量通过双花括号进行访问: ```python {{ variable}} {{ variable.key }} {{ variable.index }} {{ variable.property }} ``` `views.py`的代码如下: ```python def variable(request): username = 'Tom' age = 23 sex = True score = { 'chinese':128, 'math':149, 'english':122 } friends = ['John','Rose','Frank','Ben'] return render(request,'variable.html',locals()) ``` `variable.html`的代码如下: ```html <body> <h1>Variable</h1> <p>username:{{ username }}</p> <p>age:{{ age }}</p> <p>sex:{{ sex }}</p> <p>chinese:{{ score.chinese }}</p> <p>math:{{ score.math }}</p> <p>english:{{ score.english }}</p> <p>{{ friends.0 }},{{ friends.1 }},{{ friends.2 }},{{ friends.3 }}</p> </body> ``` ## 2.2 标签 ### 2.2.1 `for` `for`标签用于遍历列表或字典,语法结构是: ```html {% for iterate_value in sequence %} ... ... {% endfor %} {% for iterate_value in sequence %} ... ... {% empty%} ... ... {% endfor %} ``` `for`循环中内置了一组变量供用户使用: | 变量 | 描述 | | --------------------- | -------------------------------------- | | `forloop.counter` | 循环记数器,从1开始 | | `forloop.counter0` | 循环记数器,从0开始 | | `forloop.revcounter` | 反向循环记数器,最后一个为1 | | `forloop.revcounter0` | 反向循环记数器,最后一个为0 | | `forloop.first` | 当前循环为第一个时,该变量值为`True` | | `forloop.last` | 当前循环为最后一个时,该变量值为`True` | `views.py`的代码如下: ```python def forloop(request): books = [ { 'bookname': '孙子兵法大全集(超值金版)', 'price': 18.4, 'publishing': '新世界出版社', 'category': '历史' }, { 'bookname': '甲骨文丛书·拿破仑大帝(全2册) ', 'price': 119.5, 'publishing': '中信出版集团', 'category': '传记' }, { 'bookname': 'JavaScript DOM编程艺术(第2版)', 'price': 42.70, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': '精通iOS开发 第8版', 'price': 102.20, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': 'UNIX网络编程 卷1 套接字联网API(第3版)', 'price': 102.9, 'publishing': '人民邮电出版社', 'category': '计算机' }, { 'bookname': '曾国藩的正面与侧面:1+2(套装共两册)', 'price': 59.30, 'publishing': '岳麓书社', 'category': '传记' }, { 'bookname': '普京传:不可替代的俄罗斯硬汉 [Mr.Putin: Operative In The Kremlin] ', 'price': 39, 'publishing': '红旗出版社', 'category': '传记' }, ] context = { 'books':books } return render(request,'forloop.html',context) ``` `forloop.html`的代码如下: ```html <table width="900" cellpadding="10" celspacing="0" border="1"> <tr> <td>序号</td> <td>书名</td> <td>价格</td> <td>出版社</td> <td>分类</td> </tr> {% for book in books %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.bookname }}</td> <td>{{ book.price }}</td> <td>{{ book.publishing }}</td> <td>{{ book.category }}</td> </tr> {% endfor %} </table> ``` ### 2.2.2 `cycle` 在每次遇到`cycle`标记时,都会产生一个参数。第一次产生第一个参数,第二次产生第二个参数,依次类推。一旦用尽所有参数,再次循环时则产生第一个参数。其语法结构是: ```html {% cycle 'value1' 'value2' 'value3' '...'%} ``` ### 2.2.3 `if` ```html {% if condition %} ... {% endif %} 或者 {% if condition %} ... {% else %} ... {% endif %} 或者 {% if condition %} ... {% elif condition %} ... {% elif condition %} ... {% else %} ... {% endif %} ``` ### 2.2.4 `templatetag` 基本语法结构是: ```html {% templatetag templatebit%} ``` | 模板位(`templatebit`) | 说明 | | --------------------- | ---- | | `openblock` | `{%` | | `closeblock` | `%}` | | `openvariable` | `{{` | | `closevariable` | `}}` | | `opencomment` | `{#` | | `closecomment` | `#}` | ### 2.2.5 `verbatim` `verbatim`标签用于告诉`DTL`停止渲染此标签内的内容,其语法是: ```html {% verbatim%} ... {% endverbatim %} ``` ### 2.2.6 `url` `url`标签用于近回与指定路由和可选参数相匹配的绝对路径引用(不包括域名),其格式为: ```html {% url 'route_name' arg1 arg2 .. %} ``` ### 2.2.7 `include` `include`标签用于在一个模板文件中包含另外一个模板文件,其语法结构是: ```html {% include 'filename' %} ``` ### 2.2.8 `csrf_token` `csrf_token`称为令牌标签,其作用是为了防止跨域请求伪造,其原理是表单内添加一个隐藏域,其值为加密信息,在表单`POST`提交时将与服务器产生的加密信息进行匹配,匹配成功则意味合法用户。 ```html {% csrf_token %} ``` ## 2.3 过滤器 过滤器用于转换变量或标签参数的值,其语法结构是: ```html {{ value | filter}} ``` ### 2.3.1 `safe` `safe`用于标记一个字符串在输出前不需要对`HTML`标记进行转义,语法结构是: ```html {{ value | safe }} ``` ### 2.3.2 `truncatechars` 用于完成字符串的截取,其语法结构是: ```html {{ value | truncatechars:长度 }} ``` ### 2.3.3 `yesno` 将`True`,`False`和`None`(可选)值映射到以英文逗号分隔的数据,其结构为: ```html {{ value | yesno:"True时的值,False时的值,None时的值"}} ``` 最后修改:2024 年 11 月 09 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏