Flask 中的 import 和 extends 有什么区别?

what are the differences between import and extends in Flask?

正在看《Flask web开发》。 在例 4-3 中,

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

我想知道: extends 和 import 有什么区别?(我觉得它们在用法上还是挺相似的。) 在什么情况下,我会用extends还是import?

的区别。 {% extends parent.html %} 允许您呈现 parent.html 并覆盖其中定义的 {% block %},而 {% import %} 只允许您访问模板变量。

所以示例模板是扩展 base.html 并从 bootstrap/wtf.html 导入变量。把它想象成 python 的 class 继承和导入语句。

By default, included templates are passed the current context and imported templates are not. Jinja documentation

默认情况下不会缓存包含的模板,而会缓存导入的模板。

这是因为 import 通常被用作包含宏的模块。

最佳做法是在包含宏的模板上使用 import,而 include 最好在您不需要某些标记模板时使用。

当您 extend 另一个模板时,该模板控制您(被调用者控制调用者)- 只会呈现 "parent" 模板中的命名块:

{% extends "base.html" %}
{% block main_content %}
Only shows up if there is a block called main_content
in base.html.
{% endblock main_content%}

另一方面,import 只是将模板绑定到模板范围内的名称,并且您可以控制何时何地调用它(调用者控制被调用者):

{% import "bootstrap/wtf.html" as wtf %}
Some of your own template code with {{ wtf.calls() }} where it makes sense.