Django -- 模板
2018-04-01 本文已影响0人
liaozb1996
模板标签
模板标签分为两大类:
{% statement %}
{{ variable }}
控制语句
if
{% if variable %}
...
{% else %}
...
{% endif %}
for
{% for item in variable %}
{{ item }}
{% endfor %}
URL Reverse
# myapp/urls.py
from django.urls import path, re_path
from . import views
app_name = 'myapp'
urlpatterns = [
path('page/<id>', views.page, name='page'),
]
在模板中生成 URL
<a href="{% url 'myapp:page' page.id %}">Go to {{page.name}}</a>
静态文件
# 存放 static file (静态文件的目录)
# myapp/static
## 图片 myapp/static/images/
## css myapp/static/css/
## js myapp/static/js/
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}" />
</head>
<body>
<img src="{% static 'images/pic.jpg' %}" alt="picture" />
<script src="{% static 'js/base.js' %}"></script>
</body>
模板继承
{% block <name> %}{% block%}
{% extends '<template_name>' %}