【问题标题】:Django - Include app template in base templateDjango - 在基本模板中包含应用程序模板
【发布时间】:2016-02-10 07:43:48
【问题描述】:

我试图将应用结果包含在基本模板中。模板显示正确,但我没有看到任何结果。当我直接打开应用程序 url (127.0.0.1/Project/config/) 时,它会显示结果。

项目/urls.py

urlpatterns = patterns('',
    url(r'^$', 'Project.views.index'),
    url(r'^config/', DisplayChangelog),
)

配置/views.py

from config.models import Changelog

def DisplayChangelog(request):
    changes = Changelog.objects.all()
    t = loader.get_template("changelog.html")
    c = Context({'changes': changes})
    return HttpResponse(t.render(c))

模板/base.html

...
<ul class="nav navbar-nav">
{% include "changelog.html" %}
</ul>
...

模板/changelog.html

...
{% for change in changes %}
<li class="media">
    <div class="body">
    {{ change.desc }}
    <div class="date">{{ change.date }}</div>
    </div>
</li>
{% endfor %}
...

【问题讨论】:

  • 我不确定您希望看到什么。该模板在 /config/ 处使用信息呈现,这是您所期望的。它不适用于任何其他路径。
  • 我想将此结果包含在基本模板中,因为我想在框中包含的任何子页面上看到此更改。

标签: python django django-templates django-views


【解决方案1】:

首先,如果您在每个页面上都使用它们,您必须将一些变量放入您的base.html,但您还必须以某种方式传递这些变量。当然,您不会在每个视图的上下文中再添加一个对象,因此有context processors 的想法。如果这确实是您需要的,请查看文档。

在您的情况下,我认为将changes 变量添加到index 视图的上下文中并将您的changelog 包含在index 视图呈现的模板中就足够了。

所以基本上我想说的是,如果你想在模板中使用对象,你必须将它们传递给视图的上下文,即使你在包含的模板中使用它们也是如此。

【讨论】:

  • 但索引视图显示子页面之一。在这种情况下,dashboard.html。我想在 base.html 的标题中包含 changelog.html
  • 我仔细看了看 context_processors。我将 config/views.py 更改为:def DisplayChangelog(request): return {'changes': Changelog.objects.all()} 并将变量放在索引视图上:{% include "changelog.html" with changes=changes %} 谢谢
  • @user3041764 是的,这就是你需要做的。此外,您无需编写with changes=changes,因为changes 变量现在已包含在您的全局上下文对象中。
【解决方案2】:

您可以在视图中定义“更改”变量后尝试此操作:

{% include "changelog.html" with changes=changes %}

【讨论】:

  • 我将它与 context_processors 结合起来,它给出了我需要的结果。谢谢
猜你喜欢
  • 2015-03-06
  • 2012-02-09
  • 2015-06-12
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2013-12-16
  • 2011-06-02
相关资源
最近更新 更多