首页 > 解决方案 > 如何在另一个应用程序中使用来自一个应用程序的模板

问题描述

目前正在尝试制作社交应用程序。我创建了两个应用程序 Main 和 posts。我的帖子应用程序将处理创建、删除帖子、帖子列表的所有功能。我的主应用程序是我的主页,它将显示所有帖子,例如类似于 facebook 的主页。

主应用程序当前对用户进行身份验证,什么不是。我为我的帖子应用程序创建了视图和模板,现在我想将它包含在 Main 的应用程序主页上。不知道如何出去做这件事。不要求任何人编写代码,但至少给出如何实现这一点的结构。

应用程序的基本结构:

--Main_app
  --_views.py
  --templates
    --home.html
--posts_app
  --_views.py
  --templates
    --posts.html

我的 posts_app 视图当前包含的文件之一是:

def posts_list(request):
    #return HttpResponse("<h1> List a posts. </h1>")
    render(requests, "posts.html", {})

templates/posts.html 包含此文件:

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1>Posts template is working</h1>
  </body>
</html>

在我的 main_app 模板/html 中:

{% if user.is_authenticated %}
<h1>Homepage</h1>
<!-- Posts template -->
{% include "posts/templates/posts.html" %} 
{% endif %}

当时对我来说,将模板从帖子应用程序导入到主应用程序是有意义的,它会起作用。显然没有工作,所以我做了一些研究,找不到明确的解决方案,是否有称为模板继承的东西,应该将我的视图从帖子导入到 main.js 中。我不知道。任何帮助表示赞赏。

标签: djangodjango-templates

解决方案


如果您想使用相同的模板,最好的方法是在项目目录中而不是在应用程序中添加模板。

-myproject\
          -Main_app\
          -posts_app\
          -templates\
                     -template_name.html

并在设置中添加,

    TEMPLATES = [
       {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],# Add this line
        'APP_DIRS': True, 
         ........

在您看来,您可以直接参考template_name.html

另一种方法是在目录中创建模板,如

myproject\
         -Main_app\
                   -templates\
                             -Main_app\
                                        mytemplate.html
         -posts_app\

现在你可以通过引用来使用它Main_app\mytemplate.html

在这种情况下,第一个非常有效。


推荐阅读