Flask中extend与import的区别

阅读《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提问,近距离接收大牛回答,真的好激动!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 最近在看由一部小说改编而成的日剧,叫《不毛地带》。里面写到壹歧正在西伯利亚度过了十一年牢狱生涯,一直坚持活下去最终...
    独木Atree阅读 4,123评论 0 1
  • 那一年,我们都是青涩的 背着行囊 离开熟悉的家乡 带着父母的期盼 梦想沸腾 列车轰鸣着,飘向远方 回头凝望,要变成...
    风雨奇魂阅读 1,702评论 2 0
  • 最近流行一句话:“读过许多书,走过许多路,还是过不好这一生。”问题出在哪里?到底还能不能愉快地学习了? 共...
    如何猫_今城阅读 4,876评论 8 3
  • 在我心中,一直以来有一堂课,它恶梦般缠绕着我,令我感到窒息。每次上课前总是希望因为种种原因改上自习,那就是——英...
    隐形的鱼阅读 2,695评论 1 1

友情链接更多精彩内容