【问题标题】:Getting the page variable to Sonata twig templates将页面变量获取到奏鸣曲树枝模板
【发布时间】:2020-01-15 02:44:35
【问题描述】:

使用奏鸣曲模板时,PageBundle 中的各个页面旨在扩展 page.site.layout 模板,然后您可以使用 twig 标准块系统将内容放置在您喜欢的位置。但是我发现页面变量在我的页面上未定义,我试图了解页面变量如何到达它们。

我在多个模板中使用了 var_dump'ed 页面变量,但无法找到它的位置,我尝试使用谷歌搜索并没有找到任何感兴趣的内容。

{% extends page.site.layout %}

我希望 page 变量默认在每个奏鸣曲页面中可供我使用,我不确定是否需要从奏鸣曲传入页面,我有点认为它是由奏鸣曲处理的?

【问题讨论】:

    标签: php symfony sonata


    【解决方案1】:

    希望这会有所帮助,这就是我的做法。

    页面帮助服务

    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;
        }
    }
    

    Twig 扩展获取当前页面或(页面的)模板:

    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());
                }),
            ];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2019-10-17
      • 2019-03-08
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      相关资源
      最近更新 更多