Silex, using Twig in service

737 Views Asked by At

I'm creating an application in Silex. I want to use Twig to render templates in my service which is loading by Pimple. I need this for mailer class.

I started writing application based on silex-skeleton, so I have an twig environment in $app['twig']. The problem is, when I want to pass it into a service:

//app.php
$app['someModel'] = function ($app) {
    return new someModel($app['twig']);
};

When I'm writing something like this, twig stops working. All my subpages show:

Twig_Error_Loader: Template "(path).html.twig" is not defined ().

I've tried another trick:

//app.php
$app['someModel'] = function ($app) {
    return new someModel($app);
};

//someModel.php
class SomeModel
{
    private $twig;

    public function __construct($app)
    {
        $this->twig = $app['twig'];
    }
}

but that also breaks the twig. I've tried to assign and clone an $app['twig'] to another variable, then it also happens.

//app.php
$variable = $app['twig']

//app.php
$variable = clone $app['twig']

How can I use Twig in service in Silex?

1

There are 1 best solutions below

4
On
$app->register(new Silex\Provider\TwigServiceProvider(), 
  array('twig.path' => __DIR__.'/views',
));

To get more information have a look into the Silex Documentation.