gpt4 book ai didi

php - 如何将请求堆栈注入(inject) Twig 扩展

转载 作者:可可西里 更新时间:2023-11-01 01:00:27 25 4
gpt4 key购买 nike

我正在尝试创建一个扩展来呈现分页。它需要请求和路由器才能创建 URL,所以我这样做了:

服务.yml:

app.twig_extension:
class: MyBundle\Twig\MyExtension
public: false
calls:
- [setRequest, [@request_stack]]
- [setRouter, [@router]]
tags:
- { name: twig.extension }

然后在我的扩展中:

private $router;

private $request;

public function setRouter( UrlGeneratorInterface $router )
{
$this->router = $router;
}

public function setRequest(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
}

...

public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array())
{

if ( 1 == $paginator->getNumPages() )
{
return false;
}
var_dump($this->request);
die();

结果是 var_dump 打印了 null。尽管如果我在 setRequest 方法中执行 var_dump,它实际上会打印一个 Request 对象。任何的想法?谢谢!

最佳答案

构建twig扩展时,栈中还没有请求,为空。

您应该延迟从堆栈中检索请求到 renderPaginator() 方法。

服务定义:

app.twig_extension:
class: MyBundle\Twig\MyExtension
public: false
arguments: [@request_stack, @router]
tags:
- { name: twig.extension }

服务:

public function __construct(RequestStackInterface $requestStack, RouterInterface $router)
{
$this->requestStack = $requestStack;
$this->router = $router;
}

public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array())
{

if ( 1 == $paginator->getNumPages() )
{
return false;
}
var_dump($this->requestStack->getCurrentRequest());
die();
}

关于php - 如何将请求堆栈注入(inject) Twig 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28672716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com