template中 include的使用

include笔记:

  1. 有些模版代码是重复的。因此可以单独抽取出来,以后哪里需要用到,就直接使用include进来就可以了。
  2. 如果想要在include子模版的时候,传递一些参数,那么可以使用with xxx=xxx的形式。示例代码如下:
    {% include 'header.html' with username='zhiliao' %}
    

代码:

需要创建一个头部header.html文件与一个脚部footer.html文件,因为这两个文件是在重复使用的。
html文件:
header.html

footer.html

这是footer部分

index.html

Title {% include 'header.html' %}
这是中间内容{{ username }}
{% include 'footer.html' %}

company.html

Title {% include 'header.html' with username='中国' %} ------注意username两边不能有空格
这是公司的中间部分
{% include 'footer.html' %}

school.html

Title {% include 'header.html' %}
这是学校的中间部分
{% include 'footer.html' %}

views.py
from django.shortcuts import render

def index(request):
context = {
“username”:“中国”
}
return render(request,“index.html”,context=context)

def company(request):
return render(request,‘company.html’)

def school(request):
return render(request,‘school.html’)

猜你喜欢

转载自blog.csdn.net/jiating167168/article/details/89314770