首页 > 解决方案 > Django 结合来自不同应用程序的两个模板

问题描述

我有两个具有以下结构的应用程序

project->
    main app->
       templates->
           dashboard.html
    my app->
       templates->
           mydashboard.html

我想包含mydashboarddashboard,这可以使用包含模板标签。但是当我必须将一些参数传递给时出现我的问题mydashboard,假设它们被命名param1并且param2这些参数是我必须从my app应用程序加载的变量。一种可能的方法是在仪表板视图中填充这些参数mainapp并使用include标签将它们传递到mydashboard.html如下所示

def user_dashboard(request):
  ...-->here I have to get data from my app (this view is in main app and I do not want to make main app be dependent to my app
    return render(request, 'dashboard.html', {'param1': 0, 'param2': 34})

然后在 dashboard.html我添加这部分

{% is_app_installed "myapp" as is_myapp_installed %}
           {% if is_myapp_installed %}
                {% include "myappdashboard.html" with param1=param1 param2=param2 %}
           {% endif %}

似乎上述方法有效,但主要问题是使用此方法mainapp取决于myapp并且我不希望发生这种情况。还有其他方法可以在里面加载那些 param1 和 param2myapp吗?谢谢

标签: djangodjango-templatesdjango-views

解决方案


我看不到模板的详细信息,但是如果您想解耦这两个模板,我建议您重新考虑如何组织模板逻辑。尝试重新排列逻辑base_dashboard.html,在公共模板目录中添加一个片段和基本模板以在应用程序之间共享。

然后myappdashboard.htmldashboard.html可以用 扩展它{% extend base_dashboard.html %}


推荐阅读