在 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 的服务提供者类中注册此扩展:
<?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。