sonata-project / SonataPageBundle

This bundle provides a Site and Page management through container and block services
https://docs.sonata-project.org/projects/SonataPageBundle
MIT License
219 stars 210 forks source link

Create sonata_path extension #1311

Closed eerison closed 3 years ago

eerison commented 3 years ago

Create sonata_path extension

I'm using page_alias to link pages in my twig files

example

{{ path('_page_alias_some_router') }}

But in case the user remove the page I'll get an exception and it'll breaking my whole page.

then my Idea is create a TwigExtension to use this routers

example:

<?php

namespace App\Twig;

use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\RouterInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class SonataPathExtension extends AbstractExtension
{
    private $router;

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

    public function getFunctions()
    {
        return [
            new TwigFunction('sonata_path', [$this, 'sonataPath']),
        ];
    }

    public function sonataPath(
        string $name,
        array $parameters = [],
        string $defaultValue = '#',
        bool $relative = false
    ): string {
        try {
            $referenceType = $relative ? RouterInterface::RELATIVE_PATH : RouterInterface::ABSOLUTE_PATH;

            return $this->router->generate($name, $parameters, $referenceType);
        } catch (RouteNotFoundException $exception) {
            return $defaultValue;
        }
    }
}

then you can use in yours twig templates like this

{{ sonata_path('_page_alias_some_router') }}

//or with default value

{{ sonata_path('_page_alias_some_router', [], 'default_value') }}
VincentLanglet commented 3 years ago

When I look at the implementation this seems not related to Sonata (or SonataPage) at all. So I'm not sure it's a good idea to add this in this bundle.

This seems maybe better in another repository, and directly implemented by the developer inside his project.

eerison commented 3 years ago

I see, I thought to put in sonata project because others developers can have the same problem.

eerison commented 3 years ago

Then I'll close this issue for now :)