close

這篇文章中我們將說明如何在Templates 中如何與Javascript,CSS、JQuery互動。 一個網頁除了後端資料庫外,我想另一個最重要的是網頁前端外觀的呈現,而網頁前端的工作則要利用Javascript,CSS、JQuery等語言去處理,因此我需要在Templates的使用上多記錄一些東西,另外是否要學習Templates language。
我經常看這個圖然後思考一些資料流傳送的問題

(1) 在 Views 中的資料如何傳送至Templates ? 
(2) 在 Views 中如何使用Models 的資料 ? 
(3) 在 Templates 如何使用Javascript 及 JQuery ? 
以上這些問題都在章節都有答案。但還有下面問題,Templates 是前端程式,而Views 是後端程式
(4) 在 Templates中如何宣告變數及設定變數值初值 ?
答案: 有二種方法
(1)用with template tag 方法 
  例子1 : 設定初值

{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}

   例子2 : 將Models 中的值帶進來

{%with restaurant_id=restaurant.id %}
... use restaurant_id in this template section ...
{% endwith %}

 (2) 

{% my_var = "My String" %}
然後使用
<h1>{% trans my_var %}</h1>
或者
{% trans "my string" as my_var %}
{{ my_var }} {# 你可以使用my_var 變數 #}

 (5) Templates 中的變數值可以傳送至Views 嗎?
答案: 有四種方法

1. Post

傳送內容有值的form

# 在views.py 中經由
    request.POST.get('value')

2. Query Parameters

使用 //localhost:8000/?id=123

# 在views.py 中經由
 request.GET.get('id')

3. From the URL (See here for example)

使用 //localhost:8000/12/results/

# 在urls.py 中經由
  urlpatterns = patterns(... url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),...)

 # 在 views 中得到 (question_id)

def detail(request, question_id):
  ...
returnHttpResponse("blahblah")

4. Session (使用 cookie)

Downside of using session is you would have had to pass it to the view or set it earlier.

https://docs.djangoproject.com/en/1.7/topics/http/sessions/

# views.py
# 設定session變數
    request.session['uid']=123456  
# 擷取session變數
var= request.session.get['uid']

(6)使用JQuery 傳送變數值至Views(使用GET)

在urls.py 中新增
url(r'^list/$', list),
url(r'^list_ret/$', list_ret)

 在views.py 中新增

def list(request):
     return render(request, 'list.html')

def list_ret(request):
list_ret_data = request.GET.get('list')
     return render(request, 'list_ret.html')

 新增list.html 

{% load staticfiles %}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
    <head>
     <title>Django/jQuery AJAX</title>
      <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />

    <script src="{% static "jquery-3.2.1.js" %}"></script>
      <script src="{% static "jquery-ui-1.12.1.zip" %}"></script>
      <! ------- must care the path --------------------------------------------!>         
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"> </script>
<script type="text/javascript">             

        function list_Btn() {
         var list = $('#right').text();
               alert(list);
                            
         $.ajax({
           url: '/list_ret/',          
type: 'get',          
           data :{'list' : list},
           success: function(msg) {
             alert('結果'+msg);
           },
           error: function(data){
            alert('status:'+data.status); // the status code
            alert(data.responseJSON.error); // the message
           }
         });       
       }      
</script>
 </head>  

 <div id = 'right' style="width: 25%; float:right;text-align:left;font-size:20px;">
資料傳送開始
     <br>  
     <input id = 'song_Btn' type ="button" value="傳送" onClick="list_Btn()"></input>
  </div>  

</html>

 新增list_ret.html 

傳送資料回覆(任何傳送前端內容)
{{list_ret_data}}

 

這是一個最簡單的一個範例,我們可以在 class list_ret 中接收到前端所傳送過來的所有資料,然後我們就可以在後端做資料庫處理,作檔案操縱,作企業邏輯運算,作任何在後端可以做的事,運算完後將結果放入一個中間網頁再回傳到原來呼叫的網頁,如此就可以不用改變前端網頁內容而做到後端處理的非同步網頁處理方式。

<6> 從Views 傳送一個dict 去Templates 

views 

def main(request):
    ord_dict['2015-06-20']={}
    ord_dict['2015-06-20']['a']='1'
    ord_dict['2015-06-20']['b']='2'
    ord_dict['2015-06-21']={}
    ord_dict['2015-06-21']['a']='10'
    ord_dict['2015-06-21']['b']='20'

return render(request, 'list.html',locals())

 Templates(由小排至大)

<table>
{%for key, value in context.items.items|dictsort:"0.lower" %}
<tr> <td>{{ key }}</td>
<td>{{ value.a }}</td>
<td>{{ value.b }}</td>
</tr>
{% endfor %}
</table>

<6> 從Views 傳送一個list 去Templates 

 views  

def main(request):

return render(request, 'list.html',locals())

  Templates 

<table>

<tr> <td>{{ key }}</td>

</tr>
{% endfor %}
</table>

 <7> 從Views 傳送一個含有中文字的變數至Templates 

在views  第一行寫# -*- coding: utf-8 -*-,並且檔案儲存格式存成utf-8格式

# -*- coding: utf-8 -*- 

def
main(request):
x1 = "中文"
return render(request, 'list.html',locals())

  Templates 檔案儲存格式存成utf-8格式

{{X1}}

 

 

 

回Django Web 程式設計主目錄


 

 

  

     

 

 

 

 

 




 

 

 

 

arrow
arrow

    stanley 發表在 痞客邦 留言(0) 人氣()