扩展symfony模板并只覆盖一个块


Extending symfony template and overriding only one block

我在扩展Bundle的模板时遇到问题。情况如下:我在供应商中有自己的捆绑包。在我的项目中,我使用这个Bundle,我不想扩展一些模板(比如:/vvendor/company/MyBundle/src/company/MyBundle/Resources/views/Module/index.html.titch)。我想更改一个块,而不更改其他块。以下是我所做的:我在app/Resources/CompanyMyBundle/views/Module/index.html.twig中创建了覆盖模板,并扩展了供应商模板:{%extends"CompanyMyBundle:Module:index.html.titch"%}

问题是,作为回报,我得到了一个"ERR_EMPTY_REPONSE"错误。来自应用程序的模板覆盖了供应商,"CompanyMyBundle:Module:index.html.titch"部分指的是应用程序模板,而不是供应商模板,因此它扩展了自己。有没有一种方法可以在不扩展控制器和覆盖供应商控制器中的模板名称的情况下解决这个问题?

我的观点是,这将不适用于模板加载程序的工作方式。如果有对供应商模板的覆盖,它会使用它。

如果你想更改模板的某些部分,并且你拥有供应商模板的代码,最简单也是我认为正确的方法是将代码的该部分设为分部,然后在应用程序中覆盖分部。

{% include '_partial.html' with {'foo': 'bar'} %}

如果出于任何原因都不可能,则需要覆盖整个模板。

扩展Symfony内核,用于访问重写的资源:

<?php
namespace Webility'Bundle'WebilityBundle'HttpKernel;
use Symfony'Component'HttpKernel'Kernel as BaseKernel;
abstract class Kernel extends BaseKernel
{
    public function getBundle($name, $first = true)
    {
        $get_next = false;
        if($name[0] == '!' && $first){
            $name = substr($name, 1);
            $first = false;
            $get_next = true;
        }
        $bundles = parent::getBundle($name, $first);
        if($get_next){
            return isset($bundles[1]) ? $bundles[1] : $bundles[0];
        } else {
            return $bundles;
        }
    }
    public function locateResource($name, $dir = null, $first = true)
    {
        $get_next = false;
        if($name[0] == '@' && $name[1] == '!' && $first){
            $name = '@'.substr($name, 2);
            $first = false;
            $get_next = true;
        }
        $files = parent::locateResource($name, $dir, $first);
        if($get_next){
            return isset($files[1]) ? $files[1] : $files[0];
        } else {
            return $files;
        }
    }
}

然后以这种方式扩展模板:

{% extends '!WebilityAdminBundle::layout.html.twig' %}

感叹号的意思是,使用第二个找到的结果,而不是第一个。PS。不要忘记在app/AppKernel.php 中新建Kernel类