Re: [問題] 請問Django的一個用法
※ 引述《guitarpl (撞牆期)》之銘言:
: 這幾天研究Django有點心得
: 也試著做了一些內容
: 目前遇到一個問題是
: 當在某個頁面,那他相對應的Link 要加一個class = "current"
: e.g.
: <li class="current"><a href="/">Home</a></li>
: <li><a href="/about">About</a></li>
: 假如目前在home則是上面這樣
: 而在about頁面的時候則是
: <li><a href="/">Home</a></li>
: <li class="current"><a href="/about">About</a></li>
: 因為超連結的部分我都把他放在basic.html
: 其他html都是extends這個檔案
: 1. 請問有甚麼辦法可以做到我上面說的那個效果呢? {% url %}有辦法用在這個地方嗎?
: 2. Django中是否有函數可以回傳目前的網址?
: 或是有相關的文件可以參考,目前看了一些文件似乎都不能非常符合我要的效果~"~
: 先謝謝了~~
先回答第二個問題
如果你有把 RequestContext 物件傳入 template[1]
那麼你就可以在 template 中用 request 變數存取當下的 HttpRequest 物件
參見 https://docs.djangoproject.com/en/dev/ref/request-response/
視需求選用 request.path, request.get_full_path 和 request.build_absolute_uri
有了上面的東西之後, 第一個問題就簡單了
你可以寫成這樣 https://gist.github.com/uranusjr/5891821
不過上面這東西說真的實在很違反 DRY 原則
我會包成一個 inclusion tag, 像這樣 https://gist.github.com/uranusjr/5891869
如果搭配 url reverse 而不是直接寫死 MENU_PAGES 裡面的 URL 就更好
這個就讓你自己做吧
[1] 最簡單的方法是用 render shortcut 取代 render_to_response
參見 https://docs.djangoproject.com/en/dev/topics/http/shortcuts/
--
Les grandes et les meilleurs tone from "Zadok the Priest"
Eine grosse stattliche Veranstaltung by F. Handel
THE MAIN EVENT! These are the men
Sie sind die Besten
"Champions League" by Tony Britten THESE ARE THE CHAMPIONS!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.32.81.146
推
06/30 01:22, , 1F
06/30 01:22, 1F
→
06/30 01:24, , 2F
06/30 01:24, 2F
討論串 (同標題文章)