Djago模板拾起

 

 

在view中使用template:
首先在settings.py中配置模板文件的路徑。
TEMPLATE_DIRS = (
'/home/django/mysite/templates',
)



1.變量的使用
  {{ username }}

2.條件語句使用
  if 能夠使用and, or, not來組織你的邏輯。但不容許and和or同時出現的條件語句中。
  沒有{% elif %}這樣的用法,只能用嵌套來實現多重if語句。
  {% if is_logins %}
    {{ is_login }}
  {% else  %}
    <p> 123 </p>
  {% endif %}

3.循環語句  使用empty關鍵字來進行爲空時候的跳轉。
  {% for item in date_all %}
    <li>{{ item.name }}</li>
  {% empty %}
    <li>你輸入的爲空奧</li>
  {% endfor %}



4. ifequal和ifnotequal,一看就是直接比較值的tag,須要兩個參數,用法比較有限,
    只限於字符串,整數,小數的比較,什麼列表,字典,元組不支持。

      {% ifequal post.title post.body %}
                  <h1>Welcome!</h1>
                  {% endifequal %}

5.{#  #},模板註釋的用法,只能用在一行,若是要使用多行註釋,要使用{% comment %}
      {% comment %}
        hello !word!!這裏是註釋內容

      {% endcomment %}


6. 後端模板使用

  1.render_to_response
    大多數狀況下,你會使用一種shortcut方法,render_to_response()去完成以上的工做。
    from django.shortcuts import render_to_response
  2.locals() 的使用
    若是你有不少變量傳給render,一個一個構造DICT元素很麻煩,直接把變量名改爲模板中所需的變量在使用locasl()函數,輕鬆搞定。

  3.{% include %}的使用
    {% include 'index.html' %},用來引入其它模板的內容,減小重複的模板代碼
    return render_to_response('index.html',{'blog_list':'text.html'})
    {% include blog_list %} 能夠傳來變量名
    更好用的方法下
  4.{% block content %}   ##母板內容,
      {% endblock %}
      {% extends 'base.html' %}子版調用得導入母板,模板繼承
          {% block content %}
                子版內容
            {% endblock %}
相關文章
相關標籤/搜索