Django模板

在Django框架中,模板是可以帮助开发者快速生成呈现给用户页面的工具

创建模板文件夹,两种,在工程目录的需要注册settings中的TEMPLATES中的DIRS中添加os.path.join(BASE_DIR,'templates')

模板的设计方式实现了我们MVT中VT的解耦,VT有着N:M的关系,一个V可以调用任意T,一个T可以供任意V使用
模板处理分为两个过程
加载
渲染
模板主要有两个部分
HTML静态代码
动态插入的代码段(挖坑,填坑)
模板中的动态代码段除了做基本的静态填充,还可以实现一些基本的运算,转换和逻辑
模板中的变量: 视图传递给模板的数据
    遵守标识符规则
语法{{  var }}
如果变量不存在,则插入空字符串
>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Nige'})
>>> print (t.render(c))
My name is Nige.
>>> c = template.Context({'name': 'Barry'})
>>> print (t.render(c))
My name is Barry.
模板中的点语法
字典查询
>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
'Sally is 43 years old.'  
属性或者方法
>>> from django.template import Template, Context
>>> import datetime
>>> d = datetime.date(2017, 5, 2)
>>> d.year
2017
>>> d.month
5
>>> d.day
2
>>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
>>> c = Context({'date': d})
>>> t.render(c)
'The month is 5 and the year is 2017.'

>>> from django.template import Template, Context
>>> class Person(object):
...     def __init__(self, first_name, last_name):
...         self.first_name, self.last_name = first_name, last_name
>>> t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
>>> c = Context({'person': Person('John', 'Smith')})
>>> t.render(c)
'Hello, John Smith.'
方法不能有参数。
>>> from django.template import Template, Context
>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')
>>> t.render(Context({'var': 'hello'}))
'hello -- HELLO -- False'
>>> t.render(Context({'var': '123'}))
'123 -- 123 -- True'
索引 不允许负索引
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
'Item 2 is carrots.'

模板中的小弊端,调用对象的方法,不能传递参数
模板中的标签
语法 {%  tag  %}
作用
1. 加载外部传入的变量
2. 在输出中创建文本
3. 控制循环或逻辑
if 语句:
格式: {% if  表达式 %}
        语句
{% endif  %}


{%  if 表达式 %}
         语句
{% else  %}
         语句
{% endif %}
{% if 表达式 %}
             语句
  {% elif 表达式 %}
             语句
{% endif %}
判断true或false
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}
使用and or not,可结合使用,and具有更高优先权。
{% if athlete_list and coach_list %}
    <p>Both athletes and coaches are available.</p>
{% endif %}

{% if not athlete_list %}
    <p>There are no athletes.</p>
{% endif %}

{% if athlete_list or coach_list %}
    <p>There are some athletes or some coaches.</p>
{% endif %}
{% if not athlete_list or coach_list %}
<p>There are no athletes or there are some coaches.</p>
{% endif %}


{% if athlete_list and not coach_list %}
<p>There are some athletes and absolutely no coaches.</p>
{% endif %}
{% if athlete_list and coach_list or cheerleader_list %}等同于下面这种写法:
if (athlete_list and coach_list) or cheerleader_list
使用多个相同的逻辑操作关键字也是允许的,比如:
{% if athlete_list or coach_list or parent_list or teacher_list %}
使用in和not in,
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
{% endif %}
{% if user not in users %}
If users is a list, this will appear if user isn't an element of the list.
{% endif %}
使用is 和is not
{% if somevar is True %}
This appears if and only if somevar is True.
{% endif %}


{% if somevar is not None %}
This appears if somevar isn't None.
{% endif %}
for 语句:
{% for 变量 in 列表 %}
语句1 
{% empty %}
语句2
{% endfor %}

当列表为空或不存在时,执行empty之后的语句
{{ forloop.counter }} 表示当前是第几次循环,从1数数
{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{%endfor %}

{{ forloop.counter0}}表示当前是第几次循环,从0数数
{{ forloop.revcounter}}表示当前是第几次循环,倒着数数,到1停
{{ forloop.revcounter0}}表示当前第几次循环,倒着数,到0停
{{ forloop.first }} 是否是第一个  布尔值

{% for object in objects %}
    {% if forloop.first %}
        <li class="first">
    {% else %}
        <li>
    {% endif %}
    {{ object }}</li>
{% endfor %}
{{ forloop.last }} 是否是最后一个 布尔值
{% for link in links %}
{{ link }}{% if not forloop.last %} | {% endif %}
{% endfor %}


forloop.parentloop
{% for country in countries %}
  <table>
      {% for city in country.city_list %}
      <tr>
          <td>Country #{{ forloop.parentloop.counter }}</td>
          <td>City #{{ forloop.counter }}</td>
          <td>{{ city }}</td>
      </tr>
      {% endfor %}
  </table>
{% endfor %}
注释:
单行注释
{#  被注释掉的内容  #}


多行注释
{% comment %}
内容
{% endcomment %}
过滤器: {{ var|过滤器 }}
作用:在变量显示前修改
add {{ value|add:"2" }}

没有减法过滤器,但是加法里可以加负数
{{ value|add:-2 }}

lower
{{ name|lower }}
upper
{{ my_list|first|upper }}
截断:
{{ bio|truncatechars:30 }}
过滤器可以传递参数,参数需要使用引号引起来
比如join: {{ students|join:'=' }}

默认值:default,格式 {{var|default:value}}
如果变量没有被提供或者为False,空,会使用默认值
根据提供的引用内容,我无法找到关于Django运费模板的具体信息。但是,我可以为您提供一些关于Django模板的基本知识。 Django模板是一种用于生成动态网页的工具。它允许您将静态HTML与动态数据结合在一起,以便在网页上显示动态内容。在Django中,您可以使用模板来呈现数据,并将其与视图函数中的逻辑进行分离。 在Django中,您可以创建一个模板文件,其中包含HTML和模板语言。模板语言允许您在模板中插入动态数据、循环和条件语句等。您可以使用模板标签和过滤器来处理数据并进行逻辑操作。 要使用Django模板,您需要在视图函数中加载模板,并将数据传递给模板进行渲染。然后,您可以将渲染后的模板发送给客户端以显示在浏览器中。 以下是一个简单的示例,演示如何在Django中使用模板: 1. 创建一个模板文件(例如template.html),其中包含HTML和模板语言: ```html <!DOCTYPE html> <html> <head> <title>My Django Template</title> </head> <body> <h1>Welcome to {{ website_name }}</h1> <p>Today's date is {{ current_date }}</p> </body> </html> ``` 2. 在视图函数中加载模板并将数据传递给模板进行渲染: ```python from django.shortcuts import render from datetime import date def my_view(request): website_name = "My Website" current_date = date.today() return render(request, 'template.html', {'website_name': website_name, 'current_date': current_date}) ``` 3. 在urls.py中配置URL与视图函数的映射关系: ```python from django.urls import path from .views import my_view urlpatterns = [ path('my-view/', my_view, name='my-view'), ] ``` 通过访问`http://localhost:8000/my-view/`,您将看到渲染后的模板页面,其中包含动态数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值