Search code examples
symfonytwigsymfony4twig-extension

Unable to create Twig Global Variable in Symfony 4


I have already done it using Symfony 3.3 but with Symfony 4 it's not working.

App\Twig\NotifExt:

    public function getGlobals(){

    $count = 'Hello World';

    return array('count' => $count);        
}

twig_extensions.yaml:

twig:
     globals:
          'count': '%count%'

base.html.twig:

<a class="nav-item nav-link" href="#">{{ count }} </a>

I have done something similar in the previous version and it's working well, but with Symfony 4 I'm getting the following error:

You have requested a non-existent parameter "count".


Solution

  • The first step is to remove single quotes from count variable defined in twig globals.

    In your question you seems to define the count key using a parameter but to use a service (class) read How to Inject Variables into all Templates (i.e. global Variables):

    twig:
        globals:
            yourService: '@App\YourService\Class'
    

    and then refers the service method to get the count key:

    {{ yourService.getCount() }}
    

    You've many ways to do this but you can play around this simple example to get more ideas.

    If the problem it's not resolved you probably need to upgrade your question with more details on how you want to set the count key.

    PS: have you cleared the cache?