php Symfony方法在Twig模板中的结果

pbpqsu0x  于 2023-05-05  发布在  PHP
关注(0)|答案(2)|浏览(120)

有一个问题-如何在Twig模板中从服务中获得结果?
版本:Symfony 6.1.12 PHP 8.1.6
我有一个Navigation类,它用getNavigation()方法返回Navigation数组:

namespace App\Service;

use Symfony\Component\Routing\RouterInterface;

class Navigation
{
    private RouterInterface $router;
    private array $navigation = [];

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;

        $this->setNavigation();
    }

    public function setNavigation(array $nav = []): void
    {
        $this->navigation = $nav;

        if(empty($this->navigation)) {
            $this->navigation = [
                'Home' => $this->router->generate('homepage'),
                'Products' => $this->router->generate('products'),
                'Contacts' => $this->router->generate('contacts'),
            ];
        }
    }
    
    public function getNavigation(): Array
    {
        return $this->navigation;
    }
}

现在它通过调用每个Controller中的类来工作(例如:)

public function __construct(Navigation $navigation)
    {
        $this->navigation = $navigation;
    }

// #[Route('/', name: 'homepage')]
    public function index(): Response
    {
        return $this->render('home/index.html.twig', [
            'navigation' => $this->navigation->getNavigation(),
        ]);
    }

是否可以在nav.html.twig template中访问此服务,而无需每次都调用此示例?
我已经试着在服务中保存服务。yaml by

services:
    app.navigation:
        class: App\Service\Navigation

然后在twig中通过{{ app.navigation.getNavigation() }}获取访问权限,但它不起作用。
提前感谢您的回答。

4zcjmb1e

4zcjmb1e1#

有两种方法。

  1. Twig Global.您可以将服务设置为twig全局。如果你把每一页都称为服务,那就好了。Symfony Twig全球
config/packages/twig.yaml
twig:
#...
globals:
    #the value is the service's id
    navigation: '@App\\Service\\Navigation' // maybe service id app.navigation

在twig中使用:

{{navigation.getNavigation()}}

1.细枝运行时。您可以创建运行时类和twig扩展类。然后在你的twig lazily Symfony lazy twig扩展中调用这个函数
我认为你应该改变服务定义方法。看看Symfony services

cnjp1d6j

cnjp1d6j2#

在我看来,最好的方法是写一个twig扩展,然后调用服务类
https://symfony.com/doc/current/templates.html#writing-a-twig-extension

// App/Twig/NavigationExtension.php
namespace App\Twig;

use App\Service\Navigation;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class NavigationExtension extends AbstractExtension
{
    private $navigation;

    public function __construct(Navigation $navigation)
    {
        $this->navigation = $navigation;
    }

    public function getFilters(): array
    {
        return [];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('getNavigation', [$this, 'getNavigation']),
        ];
    }

    public function getNavigation()
    {
        return $this->navigation->getNavigation();
    }
}

在小枝模板中

// templates/somewhere.html.twig
<div>
    {{ getNavigation() }}
</div>

相关问题