简体   繁体   中英

Getting the page variable to Sonata twig templates

When using sonata templates, the individual pages from the PageBundle are meant to extend the page.site.layout template, then you can use twig standard block system to place things where you like. However i'm finding that the page variable is undefined on my pages and i'm trying to understand how the page variable gets to them.

Ive var_dump'ed page variable in multiple templates and just cant find where it is, i've tried googling and haven't found anything of interest.

{% extends page.site.layout %}

I expect the page variable to be available to me within each of the sonata pages by default, i'm not sure whether I need to pass page in from sonata, I kind of thought it was handled by sonata?

Hope this helps, here is how I did it.

A page helper service :

namespace App\Service;

use Sonata\PageBundle\CmsManager\CmsManagerSelectorInterface;
use Sonata\PageBundle\Model\PageInterface;
use Sonata\PageBundle\Page\TemplateManagerInterface;

class PageHelper
{
    private $cmsSelector;
    private $templateManager;

    public function __construct(
        CmsManagerSelectorInterface $cmsSelector,
        TemplateManagerInterface $templateManager
    ) {
        $this->cmsSelector = $cmsSelector;
        $this->templateManager = $templateManager;
    }

    public function getCurrentPage(): ?PageInterface
    {
        $page = $this->cmsSelector->retrieve()->getCurrentPage();
        if ($page instanceof \Sonata\PageBundle\Model\SnapshotPageProxy) {
            $page = $page->getPage();
        }

        return $page;
    }

    public function getTemplatePath(PageInterface $page): ?string
    {
        $template = $this->templateManager->get($page->getTemplateCode());
        if (null !== $template) {
            return $template->getPath();
        }

        return null;
    }
}

The Twig extension to get the current page or template (of the page):

namespace App\Service;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class TwigPageExtension extends AbstractExtension
{
    private $pageHelper;

    public function __construct(PageHelper $pageHelper)
    {
        $this->pageHelper = $pageHelper;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('current_page', function () {
                return $this->pageHelper->getCurrentPage();
            }),
            new TwigFunction('current_page_template_path', function () {
                return $this->pageHelper->getTemplatePath($this->pageHelper->getCurrentPage());
            }),
        ];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM