2013-05-03 19 views
0

因此,我對Django相當陌生,並且正在創建一些簡單的網站。現在我正在嘗試創建一個可用於託管我的其他應用程序的網站。目前,主站點通過將名稱/ URL的字典傳遞給模板來呈現導航欄。例如,這是主要的網站的views.py:在應用程序之間傳遞django上下文

from django.shortcuts import render_to_response 

navbar = [{'Home': '/'}, 
      {'Apps': '/apps/'}, 
      {'Dropdown': '', 
      'Google': 'http://www.google.com', 
      'Stackoverflow': 'http://www.stackoverflow.com'}] 

context = {'navbar': navbar} 


def home(request): 
    return render_to_response("website/home.html", context) 


def apps(request): 
    return render_to_response("website/applist.html", context) 

什麼這導致既是主視圖和應用程序列表視圖中包含有一個鏈接到website.com/,website.com/導航欄apps /,以及包含google和stackoverflow鏈接的標題爲「Dropdown」的下拉菜單。

我的問題是,我創建了另一個應用程序,其自己的視圖使用自己的上下文值呈現給其他模板。因此,例如,它可以使用:

def appview(request): 
    ## view logic... 
    context = {"users": users, "comments": comments} 
    render_to_response("app/response.html", context) 

如果我想,我可以切換了應用程序採取一種觀點認爲將取代「應用程​​序/ response.html」與「網站/ apprender.html」,即:

def appview(request, template): 
    ## view logic... 
    context = {"users": users, "comments": comments} 
    render_to_response(template, context) 

但上下文仍然只包含用戶和評論,而不是我的導航欄信息。我在想,我要補充另有說法爲,該應用程序將剛剛添加到輸入上下文,即

def appview(request, template, context): 
    ## view logic... 
    context["users"] = users 
    context["comments"] = comments 
    render_to_response(template, context) 

,但我想知道最好的做法是什麼。那麼最好的做法是什麼

回答

0

處理任何事情的最佳做法是有爭議的。創建導航欄時,我會建議以下選項之一:

  • 實施navbar作爲模板標籤。模板標籤可以加載到任何模板中,並在整個項目中生成一致的導航欄,或者只包含在base.html中。如果你想鉤入這個導航欄,你可以通過允許templatetag標記一個參數,這個參數是一個額外菜單的列表,或者是現有菜單結構的delta值。

  • 另一個解決方案,如果您的導航欄永遠不應該改變的是直接在您的base.html文件中編寫代碼,其他模板將繼承。在任何情況下更改導航欄都需要對項目進行新的提交,並且可以避免使用複雜的模板邏輯爲其生成html。

相關問題