2014年11月5日 星期三

Django筆記(3)-網頁中加入Django標籤


第一個常用標籤 : for


步驟一
修改 mysite/mysite/views.py (完整代碼如下)

from django.shortcuts import render_to_response
from django import template

def helloWorld(request):
    fruits = ['apple', 'banana', 'orange']
    return render_to_response('test.html',locals())

步驟二
更改 mysite/templates/test.html (完整代碼如下)

<html>
    <head>
        <title> test </title>
        <meta charset='utf-8'>
    </head>
    <body>
        <p>本水果攤共有{{ fruits|length }}種水果</p>
        <!-- forloop.counter可建立從1開始的索引 -->
        {% for fruit in fruits %}
            <p>第{{ forloop.counter }}個水果 : {{ fruit }}</p>
        {% endfor %}
    </body>
</html>

步驟三
開啟 server 後,
在網址列輸入 127.0.0.1:8000/helloWorld/ 觀看結果

常用 forloop         屬性   說明
forloop.counter     計數器,由1開始遞增到迭代總數
forloop.counter0    計數器,由0開始遞增到迭代總數減1
forloop.revcounter  倒數器,由迭代總數遞減到1
forloop.revcounter0 倒數器,由迭代總數減1遞減到0
forloop.parentloop  父迴圈(上一層迴圈)的forloop變量


第二個常用標籤 : if/else/endif


步驟一
修改 mysite/templates/test.html (完整代碼如下)

<html>
    <head>
        <title> test </title>
        <meta charset='utf-8'>
    </head>
    <body>
        {% if fruits.0 == 'apple' %}
            這是apple
        {% else %}
            這不是apple
        {% endif %}
        <br><br><br>
        {% if fruits.0 == 'apple' and fruits.1 != 'apple' %}
            第一個水果是蘋果,第二個水果不是蘋果
        {% endif %}
    </body>
</html>

步驟二
開啟 server 後,
在網址列輸入 127.0.0.1:8000/helloWorld/ 觀看結果

※ 注意 and 和 or 不能混用,也不能用{% if (a and b) %}


第三個常用標籤 : 註解

{# 單行註解 #}
{% comment %}多行註解{% endcomment% }


                                                                    上一篇    回目錄    下一篇

沒有留言:

張貼留言