无法在Symfony 4中创建Twig全局变量 [英] Unable to create Twig Global Variable in Symfony 4

查看:147
本文介绍了无法在Symfony 4中创建Twig全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Symfony 3.3进行了此操作,但是使用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>

我在以前的版本中做了类似的事情,并且运行良好,但是在Symfony 4中,出现以下错误:

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

您请求的参数"count"不存在.

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

推荐答案

第一步是从twig全局变量中定义的count变量中删除单引号.

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

在您的问题中,您似乎使用参数定义了count键,但要使用服务(类),请阅读如何将变量注入所有模板(即全局变量):

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'

,然后引用服务方法以获取count密钥:

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.

如果问题仍未解决,则可能需要使用有关如何设置count键的更多详细信息来升级问题.

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:您是否清除了缓存?

PS: have you cleared the cache?

这篇关于无法在Symfony 4中创建Twig全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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