代码之家  ›  专栏  ›  技术社区  ›  Hello World

如何在Django中更改模板中的子模板?

  •  0
  • Hello World  · 技术社区  · 6 年前

    我试图制作一个包含模板的模板。是否可以传递要包含的HTML文件名?

    现在我使用这个代码。

    {% include "edit_course.html" %}
    

    但我想用上下文中的值替换“edit_course.html”。

    {% include {{name}} %}    
    

    我该怎么做?

    编辑:这是我的视图.py

    from django.shortcuts import render
    def index(request):
        if request.method == "POST":
            print("POST")
            return render(request, 'main.html')
        else:
            print(request.GET.get('opt', ''))
            if request.GET.get('opt', '') == 'new_student':
                return render(request, 'main.html', {'url': 'new_profile.html',})
            elif request.GET.get('opt', '') == 'new_crew':
                pass
            elif request.GET.get('opt', '') == 'new_course':
                pass
            elif request.GET.get('opt', '') == 'edit_student':
                pass
            elif request.GET.get('opt', '') == 'edit_course':
                pass
            elif request.GET.get('opt', '') == 'report':
                pass
            else:
                pass
    
            return render(request, 'main.html')
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Max    6 年前

    将其放入模板:

    {% include url %}

    但最好将“url”重命名为“template\u name”或此字符串中的某个内容 return render(request, 'main.html', {'url': 'new_profile.html',})

        2
  •  1
  •   Milad Khodabandehloo    6 年前

    你可以通过 经过 这个 名称 属于 子模板 主模板 看法 那个 荷载 这个 主模板 这样地:

    from django.shortcuts import render
    render(request, "mainTemplate.html", context={"name":"edit_course.html"})
    

    在你的 mainTemplate.html :

    {% with name as sub_template %}
        {% include sub_template %}
    {% endwith %}