Jinja:null-master回退示例如何工作?

时间:2012-03-03 16:09:45

标签: flask jinja2

官方jinja网站的示例代码:

{% 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 %}

据我了解,当standalone为true时,将打印以下代码:

<!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 %}

当standalone为false时,会打印出来:

{% 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 %}

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

1 个答案:

答案 0 :(得分: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 %}