【问题标题】:Django: how to simplify calls for rendering templates from subdirectoryDjango:如何简化从子目录渲染模板的调用
【发布时间】:2016-12-10 18:44:27
【问题描述】:

我有几个应用程序的 django 项目。为了能够在其中一个以上使用具有通用名称的模板(如indexmenu、...、page1page2),我采用了这种模式:

app1/
    templates/
        app1/
            page1.html
            page2.html
app2/
    templates/
        app2/
            page1.html
            page2.html

在视图中我是这样使用它的:

def myview(request): # in app1
    context={'name':'John', 'surname':'Lennon'}
    return render(request,"app1/page1.html",context)

 def myview(request): # in app2
    context={'tool':'hammer', 'size':'big'}
    return render(request,"app2/page1.html",context)

它有效,但我必须在每个渲染中写下完整的应用程序名称(app1/app2/)(并且没有应用程序使用来自其他应用程序的模板或仅来自模板/(项目本身除外))并且应用程序名称实际上很长,例如 10-17 个字符(不像 app1app2 那样短)

问题:有没有办法做得更好,每个应用程序渲染不会默认为templates/,而是分别默认为templates/app1/templates/app2/等等?

感谢所有建议

【问题讨论】:

    标签: django templates django-templates


    【解决方案1】:

    一个简单的解决方案是,您可以在应用程序顶部或 settings.py 中声明路径,并在整个脚本中使用该变量,例如:

    path1 = "app1/templates/"
    path2 = "app2/templates/"
    
    def myview(request): # in app1
        context={'name':'John', 'surname':'Lennon'}
        return render(request,path1+"page1.html",context)
    
    def myview(request): # in app2
        context={'tool':'hammer', 'size':'big'}
        return render(request,path2+"page1.html",context)
    

    这也可以减少打字工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 2017-10-13
      • 2018-10-05
      • 1970-01-01
      • 2022-07-22
      • 2020-10-21
      • 2012-06-22
      • 2021-09-20
      相关资源
      最近更新 更多