Net*_*zen 7 django django-templates django-urls
我有一个base.html模板,其中包含一个链接列表.
例:
<div id="sidebar1">
<ul>
<li><a href="/" title="">Index</a></li>
<li><a href="/stuff/" title="" class="current">Stuff</a></li>
<li><a href="/about/" title="">About Me</a></li>
<li><a href="/contact/" title="">Contact Me</a></li>
</div>
Run Code Online (Sandbox Code Playgroud)
然后我在views.py中为index.html,stuff.html,about.html和contact.html提供了每个定义.这些模板中的每一个都只是从base.html模板派生而来,并设置各自的标题和内容.
我的问题是关于上面/我有一个类="当前"的东西.
我想让我所在的当前页面具有该类属性.
我可以在每个视图中设置一个不同的变量,如current_page ="about",然后在模板中与{% ifequal %}每个链接的每个类元素进行比较,但这似乎是重复工作(因为额外的视图变量).
有没有更好的办法?也许如果有一种方法来获取模板自动填充的视图函数名称,我不需要设置额外的变量?它似乎也有很多ifequals.
Ric*_*dle 16
这是一个优雅的方式,我从某个地方复制,我只希望我能记住在哪里,所以我可以给他们信用.8-)
我id为每个页面(或部分中的所有页面)分配了一个这样的:
In index.html: <body id='section-intro'>...
In faq.html: <body id='section-faq'>...
In download.html: <body id='section-download'>...
Run Code Online (Sandbox Code Playgroud)
然后id为相应的链接:
<li id='nav-intro'><a href="./">Introduction</a></li>
<li id='nav-faq'><a href="./faq.html">FAQ</a></li>
<li id='nav-download'><a href="./download.html">Download</a></li>
Run Code Online (Sandbox Code Playgroud)
在CSS中我设置了这样的规则:
#section-intro #nav-intro,
#section-faq #nav-faq,
#section-download #nav-download {
font-weight: bold;
/* And whatever other styles the current link should have. */
}
Run Code Online (Sandbox Code Playgroud)
因此,这主要以声明方式控制当前页面所属链接的样式.您可以在此处看到它:http://entrian.com/source-search/
一旦你设置它,它是一个非常干净和简单的系统,因为:
switch陈述或if / else / else陈述我没有使用Django,但这个系统可以在任何地方使用.在您的情况下,您"设置各自的标题和内容",您还需要设置body id,并且不需要其他Django标记.
这个想法也很容易扩展到其他情况,例如."除了下载页面本身,我希望每个页面的侧边栏都有一个下载链接." 你可以在CSS中这样做:
#section-download #sidebar #download-link {
display: none;
}
Run Code Online (Sandbox Code Playgroud)
而不必在条形码HTML中放置条件模板标记.
| 归档时间: |
|
| 查看次数: |
3434 次 |
| 最近记录: |