Django - 根据当前页面突出显示导航? [英] Django - Highlight Navigation based on current page?
问题描述
我正在构建一个包含几个主要部分的webapp。每个部分都有几个子部分。我有一个 main_nav.html
文件,保存主要部分的导航。这被添加到 HTML
文件中, {%include ...%}
命令在$ $ c> base.html 模板。此外,我有几个子部分的导航文件,每个都添加到任何给定的页面,具有相同的 {%include ...%}
命令。
I am building a webapp that has several main sections. Each section has several sub-sections. I have a main_nav.html
file that holds the nav for the main section. This is added to the based HTML
file with the {% include ... %}
command in the base.html
template. Further, I have several sub-section nav files, each of which are added to any given page with the same {% include ... %}
command.
所有的导航栏都非常简单,只是文本与< a href ...>
标签。
All the nav bars are very simple, just text with <a href...>
tags.
我想突出显示当前主要部分和当前子部分的链接。由于这个webapp是相当大的,我希望以某种方式这样做,而不添加页面特定的信息。另外,我希望它只是工作,因为webapp扩展包括更多的部分和子部分。例如,这可以通过查看正在使用的实际URL来完成吗?我希望将这个可以在nav文件本身内,而不必在每个django视图中加载一些变量或任何内容。
I want to highlight the link for the current main section and the current sub-section. Since this webapp is rather big, I was hoping to somehow do this without adding page-specific information. Plus, I want it to just "work" as the webapp expands to include more sections and sub-sections. For example, could this be done by looking at the actual URL in use? I was hoping to put this could within the nav files themselves and not have to load some variable or whatever within every django view.
所以,例如,导航看起来像这是:
So, for example, the nav looks like this:
(main ->) [Systems][Invoices][Work Orders][Admin]
(system sub-nav ->) [Owner][Billing][Contacts]
所以如果我在帐单
部分系统
中,我想要链接系统
以粗体和链接结算
为粗体(或其他一些简单的高亮)
So if I am in the Billing
section of Systems
, I want the link Systems
in bold and the link Billing
to be bold (or some other simple highlight)
或:
(main ->) [Systems][Invoices][Work Orders][Admin]
(Work-Orders sub-nav ->) [Create New][Outstanding]
如果我在
部分,链接工作订单
的杰出工作订单
和链接需要突出显示
。
If I am in the Outstanding
section of Work Orders
, the link Work Orders
and the link Outstanding
needs to be highlighted.
任何想法?
推荐答案
假设您使用 render_to_response
与 RequestContext
或使用Django的 render
方法或基于类的视图1.3,您将在模板中提供请求对象。从那里,只需访问当前路径并将其与预期值进行比较即可:
Assuming you use render_to_response
with RequestContext
or use the render
method or class-based views of Django 1.3, you'll have the request object available in your template. From there, it's a simple matter of just accessing the current path and comparing it with expected values:
<a href="/some/path/to/be/highlighted/"{% if request.path == '/some/path/to/be/highlighted/' %} class="active"{% endif %}>Some Link</a>
在Django 1.3中,我喜欢节省冗余,并使用 code> operator for the URL lookup:
In Django 1.3, I like to save redundancy and use the as
operator for the URL lookup:
{% url 'some_urlpattern_name' as url %}
<a href="{{ url }}"{% if request.path == url %} class="active"{% endif %}>Some Link</a>
根据需要重复每个链接。
Repeat as necessary for each link.
这篇关于Django - 根据当前页面突出显示导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!