2012-03-03 41 views
4

从官方神社网站的示例代码:Jinja:null-master回退示例如何工作?

{% if not standalone %}{% extends 'master.html' %}{% endif -%} 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<title>{% block title %}The Page Title{% endblock %}</title> 
<link rel="stylesheet" href="style.css" type="text/css"> 
{% block body %} 
    <p>This is the page body.</p> 
{% endblock %} 

据我了解,当独立的是真下面的代码印:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<title>{% block title %}The Page Title{% endblock %}</title> 
<link rel="stylesheet" href="style.css" type="text/css"> 
{% block body %} 
    <p>This is the page body.</p> 
{% endblock %} 

当独立是假的,这是印刷:

{% if not standalone %} 
<<master.html's code>> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<title>{% block title %}The Page Title{% endblock %}</title> 
<link rel="stylesheet" href="style.css" type="text/css"> 
{% block body %} 
    <p>This is the page body.</p> 
{% endblock %} 

这似乎很奇怪。我明显错过了一些明显的东西,它是什么?

回答

5

从文档中没有立即清楚的事情是,当模板扩展另一个模板时,只会呈现子模板中具有父模板中对应部分的块。其他一切都被丢弃了。

因此,在非独立模式:

{% if not standalone %} 
{% only care about blocks also in "master.html" %} 
{% endif %} 
{# Everything below is ignored #} 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<title>{# The following will be rendered if master has a block named title. #} 
{% block title %}The Page Title{% endblock %} 
{# All the following will be ignored #}</title> 
<link rel="stylesheet" href="style.css" type="text/css"> 
{# This *may* be rendered, if master.html has a block named "body" #} 
{% block body %} 
    <p>This is the page body.</p> 
{% endblock %}