在Symfony2中将Twig作为服务注入 [英] Injecting Twig as a service in Symfony2

查看:49
本文介绍了在Symfony2中将Twig作为服务注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想将标准控制器扩展,而是将Twig注入我的一个类中。

Instead of extending the standard controller, I'd like to inject Twig into one of my classes.

控制器:

namespace Project\SomeBundle\Controller;

use Twig_Environment as Environment;

class SomeController
{
    private $twig;

    public function __construct( Environment $twig )
    {
        $this->twig    = $twig;
    }

    public function indexAction()
    {
        return $this->twig->render(
            'SomeBundle::template.html.twig', array()
        );
    }
}

然后在服务中。 yml 我有以下内容:

project.controller.some:
    class: Project\SomeBundle\Controller\SomeController
    arguments: [ @twig ]

错误我得到的是:


SomeController :: __ construct()必须是Twig_Environment的实例,没有给出

SomeController::__construct() must be an instance of Twig_Environment, none given

但是我通过 config @twig c>。我看不到我在做什么错。

But I'm passing in @twig via config. I can't see what I'm doing wrong.

编辑:

添加正确的代码-这就是解决问题的方法:

Adding in the correct code - this is what fixed the problem:

// in `routing.yml` refer to the service you defined in `services.yml` 
project.controller.some
    project_website_home:
        pattern:  /
        defaults: { _controller: project.controller.some:index }


推荐答案


  1. 尝试清除缓存。

  1. Try clearing your cache.

您的路线是否设置为将控制器视为服务?否则,Symfony将不会使用服务定义,因此不会使用您指定的任何参数。

Is your route set up to refer to the controller as a service? If not, Symfony won't utilize the service definition, and therefore any arguments you specify.

这篇关于在Symfony2中将Twig作为服务注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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