2016-09-29 27 views
0

嗨,我是新來的Django,我正在嘗試做一個網站。我的項目結構,目前像這樣:有沒有什麼辦法根據當前的url在靜態導航欄模板內動態加載模板?

project/ 
    manage.py 
    project/ 
     __init__.py 
     settings.py 
     urls.py 
     myapps/ 
      __init__.py 
      main/ 
       __init__,models,views,urls,etc... 
       static/ 
        main/ 
       templates/ 
        main/ 

我使用html5boilerplate所有的CSS,JavaScript和圖像位於

myapps/main/static/main/ 

而且我所有的模板駐留在

myapps/main/templates/main/ 

具有獨特的名稱。當用戶點擊主界面他們加載與html5bp來略加修改的index.html(重命名爲boilerplate.html):

<!-- boilerplate.html --> 
{% load static %} 
... 
<body> 
    <!--[if lt IE 8]> 
     ... 
    <![endif]--> 

    <!-- Add your site or application content here --> 
    {% include "main/index.html" %} 

    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> 
    <script src="{% static 'main/js/plugins.js' %}"></script> 
    <script src="{% static 'main/js/main.js' %}"></script> 

    <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> 
    <script> 
     ... 
    </script> 
</body> 
... 

我使用index.html作爲我的靜態側邊欄,但我有在一個單獨的模板中,以防萬一我想改變它的路線,並將無聊的東西與有趣的東西分開(誰喜歡看bp代碼?)。

<!-- index.html --> 
<div id="sidenav" class="sidenav"> 
    ... 
</div> 

<div id="main"> 
    {% include /*SOMETHING HERE*/ %} 
</div> 

現在只要一個用戶被重定向到一個新的頁面我只是想解決的目標網址和改變包括標籤包括一個完全不同的模板。所以我想我必須通過請求的網址到一個視圖函數並從中返回一個模板,但我不確定如何做到這一點,或者如果它會工作。對不起,如果這是來自某個地方的重複問題,我確實看過,找不到任何相關的東西。

回答

1

你在想這個錯誤的方式:你應該使用模板繼承。您的視圖應該爲該URL呈現特定的模板,但每個模板都應該擴展index.html,它提供了側欄和結構的其餘部分。

+0

好的,我只是讀了這個。要明確我應該有index.html extends boilerplate.html,而不是在boilerplate.html中包含index.html,我應該使用{%block content%}?那麼對於我的其他頁面,我只是擴展index.html,將/ * SOMETHING HERE * /行替換爲另一個{%block content%}? – GregoryNeal