【问题标题】:How to change sub-template in template in Django?如何在 Django 中更改模板中的子模板?
【发布时间】:2018-07-23 10:19:19
【问题描述】:

我尝试制作一个包含模板的模板。是否可以传递html文件名来包含?

现在我使用这个代码。

{% include "edit_course.html" %}

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

{% include {{name}} %}    

我该怎么做?

编辑:这是我的views.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')

【问题讨论】:

  • 你试过{% include name %}吗?
  • 我已经尝试过了,但我得到了“ID 或文字预期”。
  • @HelloWorld 你能展示你的观点吗,py?
  • @Johny Beebop 我已经添加了我的views.py

标签: django django-templates django-views


【解决方案1】:

把它放到你的模板中:

{% include url %}

但最好将 'url' 重命名为 'template_name' 或此字符串中的名称 return render(request, 'main.html', {'url': 'new_profile.html',})

【讨论】:

    【解决方案2】:

    您可以通过sub_template名称传递中的主模板查看 加载 主模板 像这样:

    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 %}
    

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 2018-09-22
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2015-09-07
      • 2015-10-01
      相关资源
      最近更新 更多