我在silex应用程序中使用Twig。在预请求钩子中,我想检查用户是否已登录以及他们是否将用户对象添加到 Twig(以便我可以在菜单中呈现登录/注销状态)。
但是,在查看源代码后,似乎只能提供模板视图变量作为渲染方法的参数。我在这里错过了什么吗?
这正是我想要实现的目标:
// Code run on every request
$app->before(function (Request $request) use ($app)
{
// Check if the user is logged in and if they are
// Add the user object to the view
$status = $app['userService']->isUserLoggedIn();
if($status)
{
$user = $app['userService']->getLoggedInUser();
//@todo - find a way to add this object to the view
// without rendering it straight away
}
});
$app["twig"]->addGlobal("user", $user);
除了 Maerlyn 所说的之外,您还可以这样做:
$app['user'] = $user;
在您的模板中使用:
{{ app.user }}
您可以使用twig->offsetSet(key, value)
来预呈现值
注册树枝帮助程序时的示例
$container['view'] = function ($c) {
$view = new 'Slim'Views'Twig('.templatePath/');
// Instantiate and add Slim specific extension
$basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim'Views'TwigExtension($c['router'], $basePath));
//array for pre render variables
$yourPreRenderedVariables = array(
'HEADER_TITLE' => 'Your site title',
'USER' => 'JOHN DOE'
);
//this will work for all routes / templates you don't have to define again
foreach($yourPreRenderedVariables as $key => $value){
$view->offsetSet($key, $value);
}
return $view;
};
你可以像这样在模板上使用它
<title>{{ HEADER_TITLE }}</title>
hello {{ USER }},
Maerlyn 提供的答案是错误的,因为不需要使用 addGlobal
,因为 user
对象已经存在于 twig 中的环境全局变量中,如文档所述:
全局变量
当 Twig 桥可用时,全局变量引用
App
变量的实例。它允许访问以下方法:{# The current Request #} {{ global.request }} {# The current User (when security is enabled) #} {{ global.user }} {# The current Session #} {{ global.session }} {# The debug flag #} {{ global.debug }}
麻生太郎根据文档,例如,如果要添加任何其他称为foo
的全局,则应执行以下操作:
$app->extend('twig', function($twig, $app) {
$twig->addGlobal('foo', 127); // foo = 127
return $twig;
});
注册树枝服务后。
注册树枝服务非常简单:
$app->register(new Silex'Provider'TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));