从控制器扩展捆绑包中的所有模板

发布于 2024-12-17 00:30:40 字数 210 浏览 1 评论 0原文

我在一个捆绑包中有很多模板,它们都扩展了相同的layout.html.twig。不必

{% extends 'MyBundle::layout.html.twig' %}

在每个模板的顶部定义:有没有办法进行配置?

我怀疑我需要基于在渲染之前扩展模板的事件侦听器创建类似 pre- 或 postExecute() 的方法。

I have a lot of templates in a bundle and they all extend the same layout.html.twig. Rather than have to define:

{% extends 'MyBundle::layout.html.twig' %}

at the top of every template, is there a way to do configure this?

I suspect that I would need to create a pre- or postExecute()-like method based on an event listener that extended the template before rendering.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兰花执着 2024-12-24 00:30:40

这不是一个好主意,因为并非每个模板都必须扩展布局:有一些“系统”模板,例如 form_div_layout.html.twig 并不意味着扩展任何内容。此外,并非您编写的每个模板都必须扩展布局;您将遇到许多小型可嵌入模板从其他模板引用的用例。

如果您尝试在每个模板上强制布局,则必须编写一些逻辑来排除“系统”和可嵌入模板,以便它们不会扩展任何内容,并且您必须对布局模板执行相同的操作也是如此,这样它就不会无限延伸。在这种情况下,您将扭转问题:您必须明确声明哪些模板不应扩展您的布局,而不是显式定义要在每个模板中扩展的布局。这很快就会变得非常混乱。

为了更全面地理解这个想法,您需要知道,在幕后,模板实际上只是 PHP 类。让一个特定的类成为所有其他类的父类,然后明确声明哪些类不应该扩展该父类,这对您来说有意义吗?

但如果我还没有说服你不要走这条路,有一个 Twig 设置可以让你为所有模板设置基本模板类:

twig:
    base_template_class: Your\Layout\ClassName\Here

你可以扩展 \Twig_Template 或实现 \Twig_TemplateInterface并享受几个小时的“乐趣”,之后我希望您能被说服放弃这个想法。祝你好运。 :)

This is not a good idea, because not every template has to extend a layout: there are some “system” templates like form_div_layout.html.twig that are not meant to extend anything. Besides, not every template you write has to extend a layout; you'll encounter a lot of use cases for small embeddable templates to reference from other templates.

If you will try to force a layout on each template, you'll have to write some logic to exclude “system” and embeddable templates so that they don't extend anything, and you'll have to do the same for your layout template too, so that it doesn't extend itself infinitely. In this case you'll reverse the problem: instead of defining explicitly which layout to extend in each template, you'll have to explicitly state which templates should not extend your layout. This will get very messy very fast.

To grasp this idea more completely, you need to know that, behind the scenes, templates are really just PHP classes. Does it make sense to you to make a particular class the parent for every other classes, and then explicitly state which classes should not extend this parent?

But if I haven't convinced you not to go this way, there is a Twig setting which lets you set the base template class for all templates:

twig:
    base_template_class: Your\Layout\ClassName\Here

You can extend \Twig_Template or implement \Twig_TemplateInterface and have some “fun” for several hours, after which I hope you'll be convinced to abandon this idea whatsoever. Good luck. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文