扩展或包含 - Twig 中什么更好?Twig

2023-09-07 00:07:52 作者:9.凭栏落花侧

为什么 Twig 文档建议使用扩展而不是包含?Symfony 2 文档说因为在 Symfony2 中,我们喜欢以不同的方式思考这个问题:一个模板可以被另一个模板修饰."但仅此而已.这只是作者的心血来潮还是更多?感谢您的帮助.

Why Twig documentation recommends to use extending rather than including? Symfony 2 documentation says because "In Symfony2, we like to think about this problem differently: a template can be decorated by another one." but nothing more. It's just author's whim or something more? Thanks for help.

推荐答案

何时使用继承:

您有 50 个页面共享相同的布局 - 您创建一个 layout.twig 作为父级,每个页面都扩展该 layout.twig.所以父类是通用的,子类是特定的.

You have 50 pages sharing the same layout - you create a layout.twig as a parent, and each page extends that layout.twig. So the parent is the generic and the child is the specific.

何时使用包括:

在 50 个页面中,有 6 个页面共享一块 HTML - 您创建一个 shared-chunk.twig 并将其包含在这 6 个页面中.

Out of the 50 pages, there are 6 pages that share a chunk of HTML - you create a shared-chunk.twig and include it in those 6 pages.

另一种用法:

您注意到您的 layout.twig 有点杂乱,您想对其进行模块化,因此您将 sidebar.twig 拆分为一个单独的文件并将其包含在 layout.twig 中.

You notice that your layout.twig is bit cluttered and you would like to modularize it, so you split sidebar.twig into a separate file and include it in layout.twig.

您能否将 include 用于继承用例:

当然,为页眉、页脚和您拥有的内容创建块,并在 50 个页面中的每一页中使用包含.但如上所述,这是错误的设计.

Sure, create chunks for header, footer and what have you, and use includes in each of the 50 pages. But that's wrong design as explained above.

您能否将继承用于包含用例:

当然,在父 layout.twig 中为共享块创建一个空块,并创建一个扩展 layout.twig 并填充块块的二级子 layout-with-chunk.twig,并在其中的 6 个页面上面共享块的示例可以扩展 layout-with-chunk.twig 而不是 layout.twig.但这又是错误的设计,因为块块并非由所有子代共享,也不应该进入基础父代.此外,您还弄乱了继承树.

Sure, create an empty block for the shared chunk in the parent layout.twig, and create a second level child layout-with-chunk.twig that extends layout.twig and fills in the chunk block, and the 6 pages in the above example that share the chunk can then extend layout-with-chunk.twig instead of layout.twig. But this again is wrong design because the chunk block is not shared by all children and shouldn't go into the base parent. Plus you have cluttered the inheritance tree.

所以:

如上所述 - 这是一个设计问题,而不是可编程性问题.这不是关于:我可以使用不同的编程技术实现相同的结果,而是关于哪种用法更好的设计.

As explained above - it's a matter of design not programmability. It's not about: I can achieve this same result using a different programming technique, its about which usage is better design.