如何从自定义树枝过滤器调用内置的树枝函数?
我想创建一个自定义过滤器,该过滤器将返回HTML链接到客户端配置文件。
我需要类似的东西:
<?php
namespace App\Twig;
use App\Entity\Client;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class ClientExtension extends AbstractExtension
{
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new TwigFilter('client_link', [$this, 'createClientLink'], [
'is_safe' => ['html'],
'needs_environment' => true,
]),
];
}
public function createClientLink(Environment $environment, Client $client): string
{
// this code is an example, such function does not exist
$url = $environment->callTwigFunction('path', 'client_profile', [$client->getId()]);
return '<a href="'.$url.'">'.$client->getEmail().'</a>';
}
}
我不知道的是如何称呼PATH
twig函数?我可以使用一些calltwigfunction
类似的功能吗?
I want to create a custom filter which will return HTML link to client profile.
I need something like:
<?php
namespace App\Twig;
use App\Entity\Client;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class ClientExtension extends AbstractExtension
{
/**
* {@inheritdoc}
*/
public function getFilters(): array
{
return [
new TwigFilter('client_link', [$this, 'createClientLink'], [
'is_safe' => ['html'],
'needs_environment' => true,
]),
];
}
public function createClientLink(Environment $environment, Client $client): string
{
// this code is an example, such function does not exist
$url = $environment->callTwigFunction('path', 'client_profile', [$client->getId()]);
return '<a href="'.$url.'">'.$client->getEmail().'</a>';
}
}
What I cannot figure out is how do I call the path
twig function? Is there some callTwigFunction
-like feature I can use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经这样实现了:
多亏了@cerad 编辑的建议
:
我将保留上述代码,因为它显示了我对“呼叫内置twig”的更一般性问题的答案内部过滤器的功能”。但是,正如其他人在评论中指出的那样,我案件的正确方法是注入
urlgeneratorInterface
:然后生成这样的URL:
I have implemented it this way:
Thanks to the suggestion of @Cerad
EDIT:
I am going to keep the above code because it shows the answer to the more general question I had about "calling built-in twig functions from inside filters". However as pointed by others in the comments, the proper way for my case was to inject
UrlGeneratorInterface
:and then generate URL like this: