Django - 模板结构优化
2018-12-13 本文已影响0人
前端程序猿
接着 自定义模板过滤器 往下讲
一、引入模板
include 标签的使用
-
新建
templates/header.html<header>头部</header> -
新建
templates/footer.html<footer>尾部</footer> -
修改
templates/index.html<body> {% include 'header.html' %} <div>内容</div> {% include 'footer.html' %} </body>
include 标签中的模板查找路径
include 标签引入的模板可以引用当前模板中的变量
-
修改
front/views.pydef index(request): context = { 'title': 'Django' } return render(request, 'index.html', context=context) -
修改
templates/header.html{#头部 Django#} <header>头部 {{ title }}</header> -
但为了所有引用
templates/header.html的模板都能使用title变量, 可以在include标签中传递该变量修改
templates/index.html{#头部 Young and Beautiful#} {% include 'header.html' with title='Young and Beautiful' %}
二、模板继承
-
新建
templates/base.html:<body> {% include 'header.html' with title='Young and Beautiful' %} <div> {% block content %} 默认内容 {% endblock %} </div> {% include 'footer.html' %} </body> -
修改
templates/index.html:{% extends 'base.html' %} {% block content %} 首页中的内容 {% endblock %} -
访问
block标签被覆盖的内容:templates/index.html:{% extends 'base.html' %} {% block content %} 首页中的内容 <p>{{ block.super }}</p> {% endblock %}