阅读《Flask web development》这本书表单这一章的时候,产生了一个疑问。貌似类似引用功能的代码,一个用了extend,一个用import。想知道他们的区别在哪里。刚好一好友也有此疑问,遂上stackoverflow上去提了问,今早就收到了大牛的回答,很是惊喜,这里跟大家分享下。
what are the differences between import and extends in Flask?
I am reading 《Flask web development》. in Example 4-3,
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
I’d like to know:
What are the differences between extends and import?(I think they are quite similar in usage.)
In which situation,I will use extends or import?
Sean Vieira大神的回复:
When you extend another template the template controls you (the called controls the caller) – only named blocks in the “parent” template will be rendered:
{% codeblock %}
{% extends "base.html" %}
{% block main_content %}
Only shows up if there is a block called main_content in base.html.
{% endblock main_content%}
On the other hand an import simply binds the template to a name in your template’s scope, and you control when and where to call it (the caller controls the called):
{% import "bootstrap/wtf.html" as wtf %}
Some of your own template code with ‘wtf.calls()’ where it makes sense.
因为英语太渣,开始还不是很能理解。后来跟朋友讨论,大致明白了大神的意思。
简单翻一下就是:
extend使用base.html中规定好的字段,并只能够对其中规定的这些字段内容进行修改,所谓“the called controls the caller”.
import则用户可以选择其中的字段进行使用,是由用户对调用的模板进行控制,所谓“the caller controls the called”。
感想:第一次使用stackoverflow提问,近距离接收大牛回答,真的好激动!