0

我正在尝试获取登录页面中添加的新字段的数据。我做了什么:

  1. 修改AccountController.php登录功能添加新参数:$this->_app->login($user, $client, !empty($data['rememberme']))
  2. Userfrosting.php登录功能中,我在应用程序中设置了它:$this->client = $client;
  3. setupTwigUserVariables功能中添加了树枝全局:$twig->addGlobal("client", $this->client);

问题是在模板中,{{client.id}}什么都不返回。任何帮助将不胜感激。

4

1 回答 1

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

<?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。

于 2017-07-20T15:54:23.303 回答