2010-02-08 49 views
3

我想開發一個網站的移動和PC瀏覽器與Django。 我試圖弄清楚視圖和模板的最佳結構。 有什麼我曾嘗試:建立網站的手機和PC與Django

1)使用不同的URL(如http://example.com/mobile/http://example.com/ OR http://example.com/?c=mobile)來區分手機和PC,並將它們映射到其設置不同的模板不同的看法。根據USER_CLIENT

3)

2)在視圖中設置不同的模板中使用的視圖的包裝層,實際的視圖只是將數據返回到包裝,所述包裝設置不同的模板。

django有沒有一種常見的方法來處理這個問題?任何建議和意見?

+1

作爲用戶我希望找到下'm.example.org'或'mobile.example.org'移動網頁。 – tback 2010-02-08 16:01:20

回答

1

我會推薦解決方案3;使用裝飾器檢查客戶端用戶代理,並在移動代理的情況下返回不同的模板。

修飾器有兩個參數:普通模板和移動模板。

從你的觀點來看,返回一個字典裝飾器可以作爲上下文傳遞給渲染函數。有一個名爲'render_to'的裝飾器可以做到這一點,Google就是這樣做的。

要處理用戶需要完整版本的用例,即使從移動設備進行瀏覽,您也可以使用重定向視圖來設置裝飾器可能檢查的cookie。

0

最佳實踐:使用minidetector將額外信息添加到請求中,然後使用django的內置請求上下文將它傳遞到您的模板中。

from django.shortcuts import render_to_response 
from django.template import RequestContext 

def my_view_on_mobile_and_desktop(request) 
    ..... 
    render_to_response('regular_template.html', 
         {'my vars to template':vars}, 
         context_instance=RequestContext(request)) 

然後在模板中,您能介紹的東西,如:

<html> 
    <head> 
    {% block head %} 
    <title>blah</title> 
    {% if request.mobile %} 
    <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css"> 
    {% else %} 
    <link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css"> 
    {% endif %} 
    </head> 
    <body> 
    <div id="navigation"> 
     {% include "_navigation.html" %} 
    </div> 
    {% if not request.mobile %} 
    <div id="sidebar"> 
     <p> sidebar content not fit for mobile </p> 
    </div> 
    {% endif %> 
    <div id="content"> 
     <article> 
     {% if not request.mobile %} 
     <aside> 
      <p> aside content </p> 
     </aside> 
     {% endif %} 
     <p> article content </p> 
     </aricle> 
    </div> 
    </body> 
</html>