在Twig视图预渲染中设置变量

4
我在Silex应用程序中使用Twig。在pre request hook中,我想检查用户是否已登录,如果已登录,则将用户对象添加到Twig中(以便可以在菜单中呈现已登录/已注销状态)。
但是,查看源代码后,似乎只能将模板视图变量作为参数提供给render方法。我错过了什么吗?
以下是我想要实现的内容:
// 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
    }

});
4个回答

18
$app["twig"]->addGlobal("user", $user);

16

除了Maerlyn所说的,你还可以这样做:

$app['user'] = $user;

并在您的模板中使用:

{{ app.user }}

1
你可以使用twig->offsetSet(key, value)来预渲染数值。
例如,在注册Twig助手时。
$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 }},

Slim和Silex是不同的框架。我认为你应该先注意问题标题、正文和标签。 - Peyman Mohamadpour

0

Maerlyn提供的答案错误的,因为不需要使用addGlobal,根据文档所说,在Twig中user对象已经存在于环境全局变量中:

Global Variable

When the Twig bridge is available, the global variable refers to an instance of App Variable. It gives access to the following methods:

{# 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;
});

注册Twig服务之后

注册Twig服务就像这样简单:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接