【问题标题】:How to add dynamic templates inside a layout template in django?如何在 django 的布局模板中添加动态模板?
【发布时间】:2019-09-03 14:03:27
【问题描述】:

我想在 1 个布局中{%include%} 8 个不同的 django 模板,而不需要制作多个布局。 我的目标是减少模板文件夹中 .html 文件的总数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    {%load static%}
    <link rel="stylesheet" href="{%static 'web/css/style.css'%}">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
</head>
<body style='margin: 0px;'>
    {%include 'web/header.html'%}
    {%include 'web/personal.html'%}
    {%include 'web/footer.html'%}    
</body>
</html>

views.py

def index(request):
    template_name = 'web/index.html'
    p = personal.objects.all()
    return render(request,template_name)

def personal(request):
    template_name = 'web/personal.html'
    return render(request,template_name)

def blog(request):
    template_name = 'web/blog.html'
    return render(request,template_name)

这是我的模板
web/personal.html -> 一些 HTML
web/blog.html -> 一些 HTML
.
.
.
web/n.html -> 一些 HTML

我希望这些文件动态包含在我的布局文件中 谢谢。

【问题讨论】:

标签: django


【解决方案1】:

我认为对你的基础 html 使用不同的上下文会起作用:

views.py

def index(request):
    template_name = 'web/index.html'
    p = personal.objects.all()
    return render(request,template_name, context={"template_name":"index"})

def personal(request):
    template_name = 'web/personal.html'
    return render(request,template_name, context={"template_name":"personal"})

def blog(request):
    template_name = 'web/blog.html'
    return render(request,template_name, context={"template_name":"blog"})

.html

<!DOCTYPE html>
...
<body style='margin: 0px;'>
    {% if template_name == "index" %}
        {%include 'web/header.html'%}
    {% elif template_name == "personal" %}
        {%include 'web/personal.html'%}
    {% elif template_name == "footer" %}
        {%include 'web/footer.html'%}
    {% endif %}    
</body>
</html>

【讨论】:

  • 成功了兄弟...非常感谢你很聪明,我没想到这样 :D :D :D :D
  • 欢迎您。如果您不介意,请您标记为已回答。谢谢:)
猜你喜欢
  • 2011-03-03
  • 2019-02-21
  • 2015-06-23
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多