我正在尝试获取登录页面中添加的新字段的数据。我做了什么:
AccountController.php
登录功能,添加新参数:$this->_app->login($user, $client, !empty($data['rememberme']))
Userfrosting.php
登录功能中,我已将其设置为应用程序:$this->client = $client;
setupTwigUserVariables
功能添加了twig global:$twig->addGlobal("client", $this->client);
问题是在模板中,{{client.id}}
什么都不返回。任何帮助将不胜感激。
答案 0 :(得分:0)
在UserFrosting 4中,您应该在Sprinkle的src/Twig/
目录中创建一个Twig扩展,并将该变量添加到getGlobals
的返回值。
您的情况有点棘手,因为我不确定client
如何成为全局变量,但同时依赖于$data['client_id']
- 这似乎是一个请求参数。目前,我假设您在任何需要client
变量的请求中提交此参数。
<?php
/**
* Stack Overflow
*
* @link https://stackoverflow.com
*/
namespace UserFrosting\Sprinkle\Site\Twig;
use Interop\Container\ContainerInterface;
use UserFrosting\Sprinkle\Site\Database\Models\Client;
/**
* Extends Twig functionality for the Site sprinkle.
*
* @author Jose Luis
*/
class Extension extends \Twig_Extension
{
protected $services;
protected $config;
public function __construct(ContainerInterface $services)
{
$this->services = $services;
$this->config = $services->config;
}
public function getName()
{
return 'myproject';
}
public function getGlobals()
{
try {
$currentUser = $this->services->currentUser;
// Assumes the client_id is being submitted as a query string (url) parameter
$clientId = $this->services->request->getQueryParam('client_id');
$client = Client::where('client_id', clientId)->where('userid', $currentUser->id)->first();
} catch (\Exception $e) {
$client = null;
}
return [
'client' => $client
];
}
}
然后,您需要在Sprinkle的service provider class:
中注册此扩展程序<?php
/**
* Stack Overflow
*
* @link https://stackoverflow.com
*/
namespace UserFrosting\Sprinkle\Site\ServicesProvider;
use UserFrosting\Sprinkle\Site\Twig\Extension as JoseExtension;
/**
* Services provider for the Site sprinkle.
*
* @author Jose Luis
*/
class ServicesProvider
{
/**
* Register extended user fields services.
*
* @param Container $container A DI container implementing ArrayAccess and container-interop.
*/
public function register($container)
{
/**
* Extends the 'view' service with Jose's Twig Extension.
*/
$container->extend('view', function ($view, $c) {
$twig = $view->getEnvironment();
$extension = new JoseExtension($c);
$twig->addExtension($extension);
return $view;
});
}
}
是的,我知道这里有很多样板文件。但是,一旦你第一次设置它们,很容易在Twig环境中添加新的变量/函数/过滤器,以及将来为Sprinkle添加新服务。