模板标签
在html中,有许多的模板标签:
1 {% for i in student %} 比较符合python对象的语法。
后端返回的数据如下:
def get_tem(request,pk): t = get_template('student/test.html') html = t.render() # return HttpResponse(html) student = [ [ {'id':1,'name':'liu','age':19,'sex':'man'}, {'id':2,'name':'jia','age':20,'sex':'man'}, {'id':3,'name':'wang','age':21,'sex':'woman'} ], [ {'id': 4, 'name': 'liu', 'age': 2000, 'sex': 'man'}, {'id': 5, 'name': 'jia', 'age': 2000, 'sex': 'man'}, {'id': 6, 'name': 'wang', 'age': 2000, 'sex': 'woman'} ] ] return render(request,'student/test.html', context={ 'now': datetime.datetime.now, 'name': 'hansha', 'fun': fun, 'student':student[pk], # 'pk':pk, })
html中:
同时,通过if条件我们可以更改tr标签内部的背景颜色。
<table> <thead> <th>id</th> <th>name</th> <th>age</th> <th>sex</th> </thead> <tbody> {# <td>{{ student.0.id }}</td>#} {# <td>{{ student.0.name }}</td>#} {# <td>{{ student.0.age }}</td>#} {# <td>{{ student.0.sex }}</td>#} {% for stu in student %} <tr {% if stu.id == 1 %} style='background-color:red' {% else %} style = "background-color:green" {% endif %}> <td>{{ stu.id }}</td> <td>{{ stu.name }}</td> <td>{{ stu.age }}</td> <td>{{ stu.sex }}</td> <td>{{ forloop.counter }}</td> </tr> {% endfor %} </tbody>
</table>
可以针对不同的id进行不同的操作。效果如下:
当然,也可以从输入的url中获取参数,pk。
配置规则如下:
path('html_tem/<int:pk>/',views.get_tem,name='temp')
但是,我在html中,选择pk属性的话,并没有什么返回值。
{% for stu in student.pk %}
render中的context参数从:
context={ 'now': datetime.datetime.now, 'name': 'hansha', 'fun': fun, 'student':student, 'pk':pk, }
变化到了:
context={ 'now': datetime.datetime.now, 'name': 'hansha', 'fun': fun, 'student':student[pk], # 'pk':pk, }
2
with的使用 重命名
{% with student as tn %}
{{ tn.1.id }}
{% endwith %}
3
off关闭自动转义 on开启
{% autoescape off %}
{{html}}
{% endautoescape %}