Django:如何获取正在呈现的模板的名称 [英] Django: how to get the name of the template being rendered

查看:199
本文介绍了Django:如何获取正在呈现的模板的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这个示例中显示引导 navbar 此处

I'm implementing a bootstrap navbar as show in this example here

导航栏中的项目为< li>的,selected项目的属性为 class =active

Items in a navbar are <li>'s , the "selected" item has the attribute class="active":

  <li class="active"> <a href="#"> Link1 </a> </li>
  <li>                <a href="#"> Link2 </a> </li>

在Django中,这些项目将在一个模板中,其中包含任何应该显示的模板导航栏。我在想这样做:

In Django these items will be within a template, which gets included by any templates that are supposed to display the navbar. I'm thinking about doing it this way:

<li> <a href="/"        class="{% if template_name == "home.djhtml"    %}active{% endif %}"> Home    </a> </li>
<li> <a href="about/"   class="{% if template_name == "about.djhtml"   %}active{% endif %}"> About   </a> </li>
<li> <a href="contact/" class="{% if template_name == "contact.djhtml" %}active{% endif %}"> Contact </a> </li>

我想知道是否有内置的方式来获取 template_name (即正在渲染的模板,传递给 render_to_response(),在 views.py

I would like to know if there is a built-in way to get the template_name (that is, the template being rendered, as passed to render_to_response(), in views.py)

当然,我可以明确地添加一个 template_name 变量到 render_to_response(),这将解决问题。但是想想DRY我觉得这不应该是需要的。

Sure, I could explicitly add a template_name variable to render_to_response(), which would solve the problem. But thinking about DRY I feel this shouldn't be needed.

推荐答案

我通常使用自定义模板标签在活动标签,菜单项等中添加一个类。

I usually use a custom template tag for this use case of adding a class to the active tab, menu item, etc.

@register.simple_tag
def active_page(request, view_name):
    from django.core.urlresolvers import resolve, Resolver404
    if not request:
        return ""
    try:
        return "active" if resolve(request.path_info).url_name == view_name else ""
    except Resolver404:
        return ""

这是一个顶级导航的代码片段:

And here's a snippet from the top nav:

<ul class="nav">
    <li class="{% active_page request "about" %}"><a href="{% url "about" %}">About</a></li>
    ...
</ul>

这篇关于Django:如何获取正在呈现的模板的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆