Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating my first twig extension to provide global variables to base templates

Tags:

twig

symfony

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.

Here is what I have so far:

Extension code:

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

This give the following error:

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

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

like image 347
Bob Flemming Avatar asked Jan 13 '23 18:01

Bob Flemming


1 Answers

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

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() }}

Besides this, if the footer file is on the same site, it's better to use the {% include '...' %} tag.

like image 122
Wouter J Avatar answered Jan 16 '23 23:01

Wouter J