创建我的第一个 twig 扩展来为基础模板提供全局变量 [英] Creating my first twig extension to provide global variables to base templates

查看:24
本文介绍了创建我的第一个 twig 扩展来为基础模板提供全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to populate a variable with some HTML code and make it available to my base.html.twig file.

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

To achive this I have made a twig extension. This is my first time using twig extentions so im not sure if this is the correct way of doing things.

这是我目前所拥有的:

扩展代码:

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: Imagine\GdmBundle\Twig\GlobalFooterExtension
        tags:
            - { name: twig.extension } 

base.html.twig:

{{GlobalFooter}}

这会产生以下错误:

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

我确定我遗漏了一些非常明显的东西.如何使我的 GlobalFooterExtension 类中的 $GlobalFooter 可用于我的 base.hmtl.twig 文件?

Im sure im missing something really obvious. How do I make $GlobalFooter from my GlobalFooterExtension class available to my base.hmtl.twig file?

推荐答案

你想设置一个全局变量,而不是一个函数.

You want to set a global variable, not a function.

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

Just use getGlobals and return your variable:

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';
    }
}

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

Or, if you want to lazy load the value of the variable, create a function and change your template to:

{{ GlobalFooter() }}

<小时>

除此之外,如果页脚文件在同一个站点,最好使用{%包括 '...' %} 标签.

这篇关于创建我的第一个 twig 扩展来为基础模板提供全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆