欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Django从理论到实战(part22)--include模板标签

发布时间:2023/12/19 37 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Django从理论到实战(part22)--include模板标签 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

学习笔记,仅供参考

参考自:Django打造大型企业官网–Huang Y;

本系列Blog以应用为主,理论基础部分我在后端专栏的Django系列博客已经写过了,如果有些需要补充的知识点,我会在这个系列中,尽量详细的记录一下。



include模板标签


理论


有时候一些代码是在许多模版中是可以复用的,一般我们可以把这些重复性的代码抽取出来,就类似于Python中的函数一样,以后想要使用这些代码的时候,就通过include导入进来,例如:

# header.html <p>我是header</p># footer.html <p>我是footer</p># main.html {% include 'header.html' %} <p>我是main内容</p> {% include 'footer.html' %}

include标签寻找路径的方式,和render函数寻找模板路径的方式是一样的。

include标签包含的模版,会自动的使用主模版中的变量,如果想传入一些其他的参数到include标签包含的模板中,那么可以使用with语句:

# header.html <p>用户名:{{ username }}</p># main.html {% include "header.html" with username='huangyong' %}

实践


  • 创建模板

首先,我们在templates文件夹下创建4个模板文件header.html, footer.html, index.html, bookstore.html:


index.html:

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body>{% include 'header.html' %}<div class="content">这是中间内容{{ username }}</div>{% include 'footer.html' %} </body> </html>

bookstore:

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body>{% include 'header.html' with username='Bai' %}<div class="content">这是书店的内容</div>{% include 'footer.html' %} </body> </html>

header.html:

<header><ul><li><a href="/">首页</a></li><li><a href="{% url 'bookstore' %}">书店</a></li><li>{{ username }}</li></ul> </header>

footer.html:

<footer>这是footer部分 </footer>
  • 发起请求

向http://127.0.0.1:8000/发起请求:


点击书店:

总结

以上是生活随笔为你收集整理的Django从理论到实战(part22)--include模板标签的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。