一、模板的导入和继承
1 模板的导入 -第一步:新建一个 xx.html,把好看的模板写入 <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">重金求子</h3> </div> <div class="panel-body"> 详情点击:<a href="http://www.baidu.com">疯狂点我</a> </div> </div> -第二步:再你想用的地方 {% include 'xx.html' %} 2 模板的继承(母版) -第一步:写一个母版,写空盒子 {% block top %} {% endblock %} -第二步:某个页面要使用母版,引入,扩写盒子 {% extends 'base.html' %} {% block top %} index页面 {% endblock %}
二、静态文件相关
# 设置成静态文件的三种方式 第一种: <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> 第二种: {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> 第三种: {% load static %} <link rel="stylesheet" href="{% get_static_prefix %}bootstrap/css/bootstrap.min.css"> # 特殊用法 {% load static %} {% static "images/hi.jpg" as myphoto %} <img src="{{ myphoto }}"></img> {% load static %} {% get_static_prefix as static %} <img src="{{ static }}images/hi.jpg" alt="Hi!" />
三、inclusion_tag的使用
主要作用:通过渲染一个模板来显示一些数据
例如,Django的Admin界面使用自定义模板标签显示"添加/更改"表单页面底部的按钮。这些按钮看起来总是相同,但链接的目标却是根据正在编辑的对象而变化的。
这种类型的标签被称为"Inclusion 标签",属于自定义标签的一种。
inclusion_tag 多用于返回html代码片段
# 可以生成一片模板中的代码块 # 使用:5步 -第一步:在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag -第二步:在app中创建templatetags包(包名只能是templatetags,不能改) -第三步:在包内,新建py文件(如:my_tags.py) -第四步:写代码(inclusion_tag) # inclusion_tag,传一个模板文件 @register.inclusion_tag('left.html') def left(num): # dic={0:第0页,1:第1页,2:第2页} dic = {i: '第%s页' % i for i in range(num)} # 固定返回的必须是字典 print(dic) return {'data': dic} @register.inclusion_tag('beautiful.html') def beautiful(title, url): return {'title': title, 'url': url} -第五步使用:(模板),先load,再使用 {% load my_tags %} {% left 5%} {% beautiful '名字' '地址'%} # 它跟tag有什么不同? -tag需要再代码中写html的东西 -inclusion_tag代码跟模板分离
更多详情:https://www.cnblogs.com/liuqingzheng/articles/9509806.html