作为Web 框架, Django 需要一种很便利的方法以动态地生成HTML。最常见的做法是使用模板。
模板包含所需HTML 输出的静态部分,以及一些特殊的语法,描述如何将动态内容插入。
{ { var } }
{ % tag % }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>标题</h1> <h2>标题</h2> <h3>标题</h3> <h4>标题</h4> <h5>标题</h5> <h6>标题</h6> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> /* 无序列表 */ <ul> <li>book1</li> <li>book2</li> <li>book3</li> <li>book4</li> </ul> /* 有序列表 */ <ol> <li>book1</li> <li>book2</li> <li>book3</li> <li>book4</li> </ol> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src="Lenovo.jpg"> # 和此HTML在同一个目录下 </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="https://www.baidu.com">百度一下</a> <a href="https://www.baidu.com"><img src="Lenovo.jpg"></a> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 style = 'color: deeppink'>图书管理系统</h1> <ul> {% for book in books %} <li><a href="/book/{{ book.id }}/">{{ book.name }}</a></li> {% endfor %} </ul> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {# r: row #} <table border="1"> <tr> <td>主机名</td> <td>IP</td> </tr> <tr> <td>localhost</td> <td>127.0.0.1</td> </tr> <tr> <td>server1</td> <td>127.0.0.1</td> </tr> </table> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> 用户名: <input type="text" placeholder="username"><br/> 密码: <input type="password" placeholder="password"><br/> <input type="submit" value="登陆"> </form> </body> </html>
{% for ... in ... %} 循环逻辑 {% endfor %}
{% if ... %} 逻辑1 {% elif ... %} 逻辑2 {% else %} 逻辑3 {% endif %}
{% comment %} 多行注释 {% endcomment %}
{% include "base/left.html" %}
{% url 'name' p1 p2 %}
{% csrf_token %}