Unable to create Twig Global Variable in Symfony 4

筅森魡賤 提交于 2020-01-05 04:56:14

问题


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".


回答1:


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?




回答2:


I found something else when checking for similar issue - this might be helpful for somebody.

If you render individual blocks (with $twig->renderBlock()) rather than making full render global variables are not automatically merged, so you need to do:

        $context = $this->twig->mergeGlobals($parameters);
        $body = $template->renderBlock('body', $context);

More info: https://github.com/symfony/symfony/issues/8517#issuecomment-21238584



来源:https://stackoverflow.com/questions/51123498/unable-to-create-twig-global-variable-in-symfony-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!