【问题标题】:How to pass the context to a Django template with include?如何使用包含将上下文传递给 Django 模板?
【发布时间】:2018-10-12 16:39:40
【问题描述】:

我已经从https://docs.djangoproject.com/en/2.1/intro/tutorial01/的教程开始构建一个django项目

在完成基础教程(该教程使用一个名为“民意调查”的应用程序创建项目)后,我想构建一种可以将许多应用程序放在一起的主页。出于这个原因,我构建了一个名为“news”的应用程序,现在我正在寻找将这两个应用程序组合在一起的方法。

到目前为止,我在名为“news/base.html”的主“新闻”模板中执行此操作,并且在代码中包含了不同的应用程序。

这是我的“news/base.html”文件:

{% include 'news/index.html' %}
{% include polls_template %}
{% include 'news/footer.html' %}

'news/index.html' 和 'news/footer.html' 这两个模板只是没有参数的 html 页面,仅用于测试,它们工作正常。

polls_template 变量是我在 news.views.base 函数中创建并在上下文中传递给模板的模板变量。

这是执行此操作的视图 sn-p:

def base(request):
    t = loader.get_template('polls/index.html')
    return render(request, 'news/base.html', {'polls_template': t})

模板显示得很好,但由于没有参数,它显示一个空投票。现在我的问题是我找不到将上下文变量传递给此模板对象以填充其字段的方法。

我试图做类似的事情:

{% include polls_template with context=polls_context %}

但它不起作用。

理想情况下,我希望有一种方法可以在视图中完成所有这些操作,因为这样我就可以单独构建应用程序,然后只需使用一个视图将它们全部收集起来并将它们传递给模板。提前感谢您的帮助!

【问题讨论】:

  • 您包含的任何模板都会获得与您包含它的模板相同的上下文变量。因此,如果您的视图添加了 polls_template 所需的上下文变量,那么它们将在您渲染它们时显示出来。一世。 e.在你看来:render(request, 'news/base.html', {'polls_template': t, 'poll': Poll.objects.first()} 会给你一个poll 对象,你可以在模板中渲染。

标签: django


【解决方案1】:

Django - two views, one page 的可能重复项(忽略对 Ajax 的引用。)一个快速说明:我明白你在做什么,但你应该明白 render() 是一个快捷方式,它包括模板加载和 HttpResponse ()。如果您使用的是 render(),则不需要调用 loader()。您的函数的另一个问题是,您已将模板包含在上下文字典中。请阅读链接的帖子 b/c 有许多不同的方法,但为了完整起见,这里有一种方法来处理您正在尝试做的事情。首先,通常您会创建一个“base.html”文件作为内容的容器,它包括页眉、页脚和可能的消息模板。然后,您可以扩展 base.html 并包含其他模板。

'base.html'

     <!doctype html>
     <html lang="en">
       <head>
        {% include 'header.html' %}
        <body>
        {% include 'news.html' %}

         {% block content %}
          //to be replaced by index/polls content that extends this template//
         {% endblock %}
         </body>
         {% include 'footer.html' %}
          </html>

'index.html'

    {% extends 'base.html' %}
     {% block content %}
      <ul>
     {% for question in questions%}
       <li> {{question}}</li>
      {% endfor %}
       </ul>
     {% endblock %}

'news.html'

     <ul>
     {% for article in news %}
       <li> {{article}}</li>
      {% endfor %}
       </ul>

然后是你的函数

    def index(request):
         polls_questions = Question.objects.all()
         newest_articles = Articles.objects.filter(post=OuterRef('pk')).order_by('-created_at')
         return render(request, 'index.html', {'questions' : polls_questions, 'news': newest_articles})

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2016-06-29
    • 1970-01-01
    • 2014-03-10
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多