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

Bob*_*ing 4 symfony twig

我需要使用一些HTML代码填充变量,并将其提供给我的base.html.twig文件.

为了实现这一点,我做了一个枝条扩展.这是我第一次使用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';
    }

}
Run Code Online (Sandbox Code Playgroud)

config.yml:

services:  

    imagine.twig.GlobalFooterExtension:

        class: Imagine\GdmBundle\Twig\GlobalFooterExtension
        tags:
            - { name: twig.extension } 
Run Code Online (Sandbox Code Playgroud)

base.html.twig:

{{GlobalFooter}}
Run Code Online (Sandbox Code Playgroud)

这会给出以下错误:

Twig_Error_Runtime: Variable "GlobalFooter" does not exist in "ImagineGdmBundle:Default:product.html.twig" at line 2
Run Code Online (Sandbox Code Playgroud)

我确定我错过了一些非常明显的东西 如何将我的GlobalFooterExtension类的$ GlobalFooter提供给我的base.hmtl.twig文件?

Wou*_*r J 8

您想要设置全局变量,而不是函数.

只需使用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';
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{{ GlobalFooter() }}
Run Code Online (Sandbox Code Playgroud)

除此之外,如果页脚文件位于同一站点,则最好使用该{% include '...' %}标记.