您现在的位置是: 网站首页 >Django Django

Django模板中include用法

admin2018年11月15日 17:16 Django | Python 1217人已围观

# Django模板中include用法 https://www.cnblogs.com/zf-l/p/django-include.html `include`标签允许在模板中包含其他的模板内容。标签的参数是所要包含的模板名称,可以是一个变量,也可以是用单/双引号硬编码的字符串。 每当在多个模板中出现相同的代码时,就应该考虑是否要使用`{% include %}`来减少重复 ## include 首选需要创建一个模板文件test.html ```html <!--test.html--> <div> 这是一个子模板 </div> ``` 然后只需要在父模板中使用`include`引入这个子模板即可 ```html <!--父模板--> <div> <h2>标题</h2> {% include 'test.html' %} </div> ``` 最后访问这个模板就会自动加载为 ```html <!--父模板--> <div> <h2>标题</h2> <!--test.html--> <div> 这是一个子模板 </div> </div> ``` 默认情况下,子模板可以访问父模板的变量 ## include with with 关键字给子模版指定变量 ```html <!--父模板--> <div> <h2>标题</h2> {% include 'test.html' with title='title1' content='content1' %} {% include 'test.html' with title='title2' content='content2' %} </div> ``` 使用模板过滤器修改变量,预览为正文取30个字符后面加`...` ```html {% include 'test.html' with title='title1' preview=content|truncatewords:30|add:' ...' %} ``` 阻止子模版访问除了 with 指定的变量 ```html {% include 'test.html' with title='title1' content='content1' only %} ``` 那么子模板中就只能使用with申明的变量了。 ## with 单独的 with 标签来修改或者指定变量的值。 ```html {% with title='title1' content='content1' %} {% include 'test.html' %} {% endwith %} {% with content|truncatewords:30|add:' ...' as preview %} {% include 'test.html' %} {% endwith %} ```

很赞哦! (1)

文章交流

  • emoji
0人参与,0条评论

当前用户

未登录,点击   登录

站点信息

  • 建站时间:网站已运行2076天
  • 系统信息:Linux
  • 后台程序:Python: 3.8.10
  • 网站框架:Django: 3.2.6
  • 文章统计:256 篇
  • 文章评论:60 条
  • 腾讯分析网站概况-腾讯分析
  • 百度统计网站概况-百度统计
  • 公众号:微信扫描二维码,关注我们
  • QQ群:QQ加群,下载网站的学习源码
返回
顶部
标题 换行 登录
网站