创建我的第一个分支扩展,为基础模板提供全局变量



我需要用一些HTML代码填充一个变量,并使其可用于我的base.HTML.twig文件。

为了实现这一点,我做了一个树枝延伸。这是我第一次使用树枝扩展,所以我不确定这是否是正确的做事方式。

以下是我目前所拥有的:

扩展代码:

class GlobalFooterExtension extends Twig_Extension
{
    public function getFilters()
    {
        return array(
            new Twig_Filter_Function('GlobalFooter', array($this, 'GlobalFooter')),
        );
    }       
    public function GlobalFooter()
    {
        $GlobalFooter = file_get_contents('http://mysite.co.uk/footer/footer.html.twig');
        return $GlobalFooter;
    }

    public function getName()
    {
        return 'GlobalFooter_extention';
    }
}

config.yml:

services:  
    imagine.twig.GlobalFooterExtension:
        class: ImagineGdmBundleTwigGlobalFooterExtension
        tags:
            - { name: twig.extension } 

base.html.trick:

{{GlobalFooter}}

这会产生以下错误:

Twig_Error_Runtime: Variable "GlobalFooter" does not exist in "ImagineGdmBundle:Default:product.html.twig" at line 2

我确信我错过了一些非常明显的东西。如何使GlobalFooterExtension类中的$GlobalFooter可用于我的base.hmtl.trick文件?

您想要设置一个全局变量,而不是函数。

只需使用getGlobals并返回您的变量:

class GlobalFooterExtension extends Twig_Extension
{
    public function getGlobals()
    {
        return array(
            "GlobalFooter" => file_get_contents('http://mysite.co.uk/footer/footer.html.twig'),
        );
    }
    public function getName()
    {
        return 'GlobalFooter_extention';
    }
}

或者,如果您想延迟加载变量的值,请创建一个函数并将模板更改为:

{{ GlobalFooter() }}

除此之外,如果页脚文件在同一个站点上,最好使用{% include '...' %}标记。

将函数getFilters重命名为getFunctions

最新更新