【问题标题】:Django: how to get the name of the template being renderedDjango:如何获取正在渲染的模板的名称
【发布时间】:2013-10-16 14:48:36
【问题描述】:

我正在实现bootstrap navbar,如本例中所示here

导航栏中的项目是 <li>'s ,“选定”项目具有属性 class="active"

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

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

<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(即正在渲染的模板,在views.py 中传递给render_to_response()

当然,我可以将template_name 变量显式添加到render_to_response(),这样就可以解决问题。但是考虑到 DRY,我觉得这不应该是必要的。

【问题讨论】:

  • 显式优于隐式:)
  • 你不应该硬编码你的模板中的url(使用{% url %}模板标签代替),你应该依赖url和request.path——而不是模板名称——来检查链接是否处于活动状态。
  • 感谢@bruno 指出这一点,我会改变的。

标签: django twitter-bootstrap django-templates twitter-bootstrap-3 navbar


【解决方案1】:

我通常使用自定义模板标签来将类添加到活动选项卡、菜单项等。

@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 ""

这是来自顶部导航的 sn-p:

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

【讨论】:

  • 谢谢。我应该如何访问request 对象:将其作为dictionary 变量传递给render()
  • @slumtrimpet 有。它由RequestContext 提供,假设您在模板渲染中使用它(Django Class Based Views 会自动这样做)。
  • 如果你使用 url 命名空间,实际上你应该在这里使用resolve(request.path_info).view_name 而不是url_name
【解决方案2】:

我用:

class="{% if 'about' in request.path %}active{% endif %}"

如果 URI 发生变化,它会更短且更健壮,只要注意是否有多个路径使用 about。

【讨论】:

    【解决方案3】:

    有一种更快的方法,无需创建任何自定义模板标签!

    <ul class = 'nav'>
        <li class="{% ifequal request.path 'about/'%} active {% endifequal%}">
            <a href="{% url "about" %}">About</a>
        </li>
    </ul>
    

    请注意 request.path。路径的开头可能有斜杠符号,也可能没有路径的结尾!

    【讨论】:

      【解决方案4】:

      附加 prog.Dusans Django 1.7 的答案

      settings.py
      TEMPLATE_CONTEXT_PROCESSORS = (
          'django.core.context_processors.request',
          'django.contrib.auth.context_processors.auth'
      )
      
      views.py
      from django.shortcuts import render
      
      def index(request):
          return render(request, 'index.html')
      
      template
      {% ifequal request.path '/pathname'%}active{% endifequal%}
      

      最好将其添加到基本模板中,这样您只需执行一次。

      像我这个版本比Kevin Stones 多,因为你必须在模板中添加几乎相等的代码,毕竟不需要模板标签。

      【讨论】:

        猜你喜欢
        • 2016-08-14
        • 2021-11-25
        • 2018-10-05
        • 2011-08-02
        • 1970-01-01
        • 2018-03-10
        • 1970-01-01
        • 2014-02-07
        • 2017-10-13
        相关资源
        最近更新 更多