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

前端 未结 2 500
自闭症患者
自闭症患者 2021-01-06 07:50

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

相关标签:
2条回答
  • 2021-01-06 08:07

    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.

    0 讨论(0)
  • 2021-01-06 08:09

    rename function getFilters to getFunctions

    0 讨论(0)
提交回复
热议问题