Django模板

模板应用实例

HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- settings.py
|   |-- urls.py
|   |-- view.py
|   |-- wsgi.py
|-- manage.py
`-- templates
    `-- hello.html

Django模板文件路径说明:

  修改HelloWorld/settings.py,修改 TEMPLATES 中的 DIRS 为 [ os.path.join(BASE_DIR,'templates') ]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

Django模板中数据库连接说明:

  修改HelloWorld/settings.py中的DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

hello.html 文件代码如下:

  <h1>{{ hello }}</h1>    #  hello是变量,{{ hello }}

from django.shortcuts import render
 
def hello(request):
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, 'hello.html', context)

使用 render 来替代之前使用的 HttpResponse。render 还使用了一个字典 context 作为参数。context 字典中元素的键值 "hello" 对应了模板中的变量 "{{ hello }}"。

Django模板标签

if / else 基本语法(支持嵌套)

{% if condition1 %}
   ... display 1
{% elif condition2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

{% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反( not )

{% if athlete_list and coach_list %}
     athletes 和 coaches 变量都是可用的。
{% endif %}  

for 基本语法

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

给标签增加一个 reversed 使得该列表被反向迭代:

{% for athlete in athlete_list reversed %}
...
{% endfor %}

可以嵌套使用 {% for %} 标签:  

{% for athlete in athlete_list %}
    <h1>{{ athlete.name }}</h1>
    <ul>
    {% for sport in athlete.sports_played %}
        <li>{{ sport }}</li>
    {% endfor %}
    </ul>
{% endfor %}

for循环实例

############ view.py #############
    from django.shortcuts import render
    def home(request):
        List = map(str,range(100))
        return render(request, 'home.html', {'List': List})
    
############## home.html #########
    <span>
        {% for item in List %}
            {{ item }}{% if not forloop.last %},{% endif %}
        {% endfor %}
    </span>
forloop.counter	        索引从 1 开始算
forloop.counter0	索引从 0 开始算
forloop.revcounter	索引从最大长度到 1
forloop.revcounter0	索引从最大长度到 0
forloop.first	        当遍历的元素为第一项时为真
forloop.last	        当遍历的元素为最后一项时为真
forloop.parentloop	用在嵌套的 for 循环中,获取上一层 for 循环的 forloop     

当列表中可能为空值时用 for  empty

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>抱歉,列表为空</li>
{% endfor %}
</ul> 

ifequal/ifnotequal 标签

{% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。

下面的例子比较两个模板变量 user 和 currentuser :

{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}

和 {% if %} 类似, {% ifequal %} 支持可选的 {% else%} 标签:

{% ifequal section 'sitenews' %}
    <h1>Site News</h1>
{% else %}
    <h1>No News Here</h1>
{% endifequal %}

注释标签

Django 注释使用 {# #}      {# 这是一个注释 #}

过滤器

模板过滤器可以在变量被显示前修改它,过滤器使用管道字符:

    {{ name|lower }}      # {{ name }} 变量被过滤器 lower 处理后,文档大写转换文本为小写。

过滤管道可以被* 套接* ,既是说,一个过滤器管道的输出又可以作为下一个管道的输入:

    {{ my_list|first|upper }}    # 将第一个元素并将其转化为大写。

有些过滤器有参数,过滤器的参数跟随冒号之后并且总是以双引号包含:

    {{ bio|truncatewords:"30" }}    # 将显示变量 bio 的前30个词。

其他过滤器:
    addslashes : 添加反斜杠到任何反斜杠、单引号或者双引号前面。

    date : 按指定的格式字符串参数格式化 date 或者 datetime 对象:   {{ pub_date|date:"F j, Y" }}

    length : 返回变量的长度。

include 标签

  {% include %} 标签允许在模板中包含其它的模板的内容。

  {% include "nav.html" %}    # 包含了 nav.html 模板:

原文地址:https://www.cnblogs.com/sshcy/p/8985670.html