Django 04
在django开发中,我们返回给用户的HTML页面通常是用模板+数据渲染出来的.这样可以减少在大量页面中重复写相同的HTML内容.
Template API
Template对象调用render方法进行渲染, 需要传入Context对象(数据).
from django.template import Template
from django.http import HttpResponse
template = Template("hello, {{ name }}.")
context = Context({"name": "LiuShuo"})
content = template.render(context)
response = HttpResponse(content)
实际项目中模板的内容, 放在模板文件中, 但我们不需要使用open, read的方式将内容读入来构造Template对象, 可以直接使用模板引擎的get_template方法.
template = get_template('blog/index.html')
提供一些快捷函数, 封装了上述获取模板+渲染+构造Httpresonse的过程.
from django.shortcuts import render, render_to_response
response = render_to_response('blog/index.html', {'name': 'LiuShuo', 'age': 33})
# render比render_to_response多了参数request, request可以在模板中使用.
response = render(request, 'blog/index.html', {'name': 'LiuShuo', 'age': 33})
模板语法
- 引用变量:
{{ name }}
<!--对象属性 or 字典键-->
{{ book.price }}
<!--对象方法, title.upper()-->
{{ title.upper }}
<!--数字索引, students[3]-->
{{ students.3 }}
Django模板系统会把{{}}
内的部分当作变量,在context内搜索变量,用变量的值替换当前{{}}
的部分。如果变量不存在就会被替换为空。
- 标记 Tags:
- for:
{% for %} ... {% endfor %}
- for:
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
- if / elif / else:
{% if %} {% elif %} {% else %} {% endif %}
<li>
{% if student.score > 90 %}
{{ student.name }} 成绩:优秀
{% elif student.score > 60 %}
{{ student.name }} 成绩:及格
{% else %}
{{ student.name }} 成绩:不及格
{% endif %}
</li>
- 模板继承&组合:
{% extends 'base.html' %}
{% block block_name %} ... {% endblock %}
<!-- base.html -->
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
<!-- child.html -->
{% extends "base.html" %}
{% block title %}LiuShuo's blog{% endblock %}
{% block content %}
{% for blog in blogs %}
<h2>{{ blog.title }}</h2>
<p>{{ blog.body }}</p>
{% endfor %}
{% endblock %}
{% include 'part.html' %}
<!-- base.html -->
<html>
<head>
{% inlcude 'head.html' %}
</head>
<body>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
<!-- head.html -->
<meta charset="utf-8">
<meta http-equiv="Content-Language" content="en">
<link rel="stylesheet" type="text/css" href="github-syntax-highlight.css">
<script type="text/javascript" src="jquery.js"></script>