Twig_Error_Syntax:函数“is_granted”不存在

问题描述 投票:5回答:5

我正在使用Silex,不能在模板中使用is_granted函数。我在文档中找不到有关为什么这不起作用的任何内容。任何提示?

$app->register(new Silex\Provider\SecurityServiceProvider());

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

$app['debug'] = true;

$app['security.firewalls'] = array(
    'login' => array(
                'pattern' => '^/login$',
        ),
        'secured' => array(
                'pattern' => '^.*$',
                'form' => array('login_path' => '/login', 'check_path' => '/login_check'),
                'users' => array(
                        'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg=='),
                ),
        ),
);

$app->get('/', function() use ($app) {
    return $app['twig']->render('index.html.twig');
});

$app->get('/login', function(Request $request) use ($app) {
    return $app['twig']->render('login.html.twig', array(
            'error'                 => $app['security.last_error']($request),
            //'last_username' => $app['session']->get('_security.last_username'),
    ));
});
twig silex
5个回答
9
投票

显然,我还需要添加symfony / bridge组件:

将其添加到composer.json并更新。

"symfony/twig-bridge": "2.1.*",

嘿......它会像预期的那样工作。


4
投票

我不得不使用这种解决方法(不知道是否有任何缺点)

$function = new Twig_SimpleFunction('is_granted', function($role) use ($app){
    return $app['security']->isGranted($role);
});
$app['twig']->addFunction($function);

2
投票

根据Symfony\Component\Security\Core\SecurityContextInterfacewewe必须提供我们试图评估的权利的第二个参数。第二个参数将被发送给选民(例如用户)

$function = new Twig_SimpleFunction('is_granted', function($role, 
$object = null) use ($app){
    return $app['security']->isGranted($role, $object);
});
$app['twig']->addFunction($function);

0
投票

问题很可能是由注册类的顺序引起的。顺序应该是SecurityServiceProvider,然后启动你的应用程序,然后注册TwigServiceProvider。 TwigServiceProvider检查$ app ['security']以设置Twig SecurityExtension。订单很重要

// Security service
$app["security.firewalls"] = array();
$app->register(new Silex\Provider\SecurityServiceProvider());

// Boot your application to call SecurityServiceProvider()->boot()
$app->boot();

// Twig service
$app->register(new Silex\Provider\TwigServiceProvider(), array(
  'twig.path' => sprintf("%s/../views", __DIR__),
));

0
投票

如果您使用Symfony 2.6组件,它将成为security.authorization_checker而不是安全性,如:

$function = new Twig_SimpleFunction('is_granted', function($role,$object = null) use ($app){
    return $app['security.authorization_checker']->isGranted($role,$object);
});
$app['twig']->addFunction($function);
© www.soinside.com 2019 - 2024. All rights reserved.