0

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?

Jakub Zawiślak
  • 5,122
  • 2
  • 16
  • 21

1 Answers1

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

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

Ralf Hertsch
  • 1,277
  • 1
  • 10
  • 15
  • I have registered Twig provider, like [here](https://github.com/silexphp/Silex-Skeleton/blob/master/src/app.php) and my site is normally working. The problem is, twig breaks when I try to put it in the service. – Jakub Zawiślak Jun 27 '14 at 22:26
  • What do you mean with 'twig breaks'? – Ralf Hertsch Jun 27 '14 at 23:08
  • When I put $app['twig'] to a service by pimple, then all my subpages which before normally working, show: Twig_Error_Loader: Template "(path).html.twig" is not defined (). – Jakub Zawiślak Jun 28 '14 at 08:38
  • I assume you have a problem with dependency injection, a proper way is like this: `use Silex\Application; class Sample { protected $app = null; public function __construct(Application $app) { $this->app = $app; } }` – Ralf Hertsch Jun 28 '14 at 09:00