模板的进阶使用

bigzhu posted @ Jun 02, 2007 09:54:00 PM in django , 1452 阅读

模板多了,需要减少冗余,尽量坐到重用

不但可以减少输入量,也可以方便管理.

一个模板中可以include另外一个模板
被引入模板的名字可以用单/双引号括起来
{% include 'nav.html' %}
{% include "nav.html" %}
也可以放到变量里面
{% include template_name %}
程序自然是到指定的TEMPLATE_DIRS 中去找模板,所以引入的时候也可以带路径
被引入的模板如果需要填充,则用父模板的context来填充.
模板可以继承


include 模板还是以新页面作为主题,重用模板作为组件来添加
而继承则是以重用模板作为主体,修改的内容作为添加内容来组合出页面.
比如,建立下面一个用来被继承的模板:




{% block title %}{% endblock %}


My helpful timestamp site


{% block content %}{% endblock %}
{% block footer %}


Thanks for visiting my site.


{% endblock %}

注意看
里面有很多以block 开头的标签,并且每个都以endblock 作为结束.

每个block都是需要继承的模板来填充不同内容的地方.

block后面的名字,可以当作block的变量名.

下面是两个填充的例子:

{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}

It is now {{ current_date }}.


{% endblock %}

{% extends "base.html" %}
{% block title %}Future time{% endblock %}
{% block content %}

In {{ hour_offset }} hour(s), it will be {{ next_time }}.


{% endblock %}

最开始的extends 标签表明了这是一个继承模板,并制定了继承自哪个模板.

指定每个block块中的填充内容.完成继承

需要统一改动的时候,只需要修改base.html就可以.


boardmodelpaper.com 说:
Jan 10, 2024 11:09:57 AM

A sample or model question paper created by educational boards or other institutions for a variety of exams is commonly referred to as the Board model paper. These practice papers give students a sense of the format, degree of difficulty, and kind of material that may be covered in the real exam, helping them get ready for exams. Typically, model papers are written for particular courses or subjects. They cover boardmodelpaper.com a variety of subjects and chapters that are anticipated to have been studied by students during the course of the semester. These educational board model papers are a common component of test-preparation strategies used by students, as they enable them to improve their comprehension of the subject matter


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter