Django结合两个来自不同应用程序的模板

时间:2018-09-16 19:10:44

标签: django django-templates django-views

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

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

我想将mydashboard包含在dashboard中,那么可以使用包含模板标记来实现。但是当我必须将一些参数传递给mydashboard时,我的问题出现了,假设它们分别名为param1param2,这些参数是我必须从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,我不希望发生这种情况。 还有其他方法可以在myapp中加载那些param1和param2吗? 谢谢

1 个答案:

答案 0 :(得分:1)

我看不到模板的详细信息,但是如果要分离两个模板,我建议您重新考虑如何组织模板逻辑。尝试重新排列在带有摘要和基本模板的通用模板目录中添加base_dashboard.html以便在应用程序之间共享的逻辑。

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

相关问题