Skip to content

Instantly share code, notes, and snippets.

@igorw
Created April 21, 2011 00:05
Show Gist options
  • Save igorw/933384 to your computer and use it in GitHub Desktop.
Save igorw/933384 to your computer and use it in GitHub Desktop.
Silex app with global Twig layout
<?php
require __DIR__.'/silex.phar';
$app = new Silex\Application();
$app->register(new Silex\Extension\TwigExtension(), array(
'twig.path' => __DIR__.'/views',
'twig.class_path' => __DIR__.'/vendor/twig/lib',
));
$app->before(function () use ($app) {
$app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.twig'));
});
$app->match('/', function () use ($app) {
return $app['twig']->render('index.twig');
});
$app->run();
{% extends layout %}
{% block content %}
<h1>Ponies</h1>
<p>
are awesome.
</p>
{% endblock %}
<!DOCTYPE HTML>
<html>
<head>
<title>Nice title here</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
@benmatselby
Copy link

This no longer seems to work. Is this deprecated now in Silex/Twig? I get:

"LogicException: Unable to add global "layout" as the runtime or the extensions have already been initialized."

@benmatselby
Copy link

The issue seems to be in the Twig/Environment::addGlobal function. This now checks if "layout" in the example above is in the $this->globals array which it isn't, and you get into this if statement because runtimeInitialized gets set because loadTemplate is called.

So you seem to have to change the above code from:

$app->before(function () use ($app) {
    $app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.twig'));
});

to

$app->before(function () use ($app) {
    $app['twig']->addGlobal('layout', null);
    $app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.twig'));
});

So, get the layout global in the array so you can update it later. Is this valid, or something else amiss here?

@feamsr00
Copy link

feamsr00 commented Feb 9, 2018

Hi There! Did you ever figure out what was going on here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment