Php 将页面变量获取到Sonata细枝模板
使用sonata模板时,PageBundle中的各个页面旨在扩展page.site.layout模板,然后您可以使用twig标准块系统将内容放置在您喜欢的地方。然而,我发现页面变量在我的页面上是未定义的,我试图理解页面变量是如何到达它们的 Ive变量在多个模板中转储了页面变量,只是找不到它在哪里,我尝试过谷歌搜索,但没有找到任何感兴趣的内容Php 将页面变量获取到Sonata细枝模板,php,symfony,sonata,Php,Symfony,Sonata,使用sonata模板时,PageBundle中的各个页面旨在扩展page.site.layout模板,然后您可以使用twig标准块系统将内容放置在您喜欢的地方。然而,我发现页面变量在我的页面上是未定义的,我试图理解页面变量是如何到达它们的 Ive变量在多个模板中转储了页面变量,只是找不到它在哪里,我尝试过谷歌搜索,但没有找到任何感兴趣的内容 {% extends page.site.layout %} 默认情况下,我希望在每个sonata页面中都可以使用page变量,我不确定是否需要从sona
{% extends page.site.layout %}
默认情况下,我希望在每个sonata页面中都可以使用page变量,我不确定是否需要从sonata传入page,我认为它是由sonata处理的?希望这有帮助,下面是我的操作方法 页面助手服务:
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;
}
}
获取当前页面或(页面的)模板的细枝扩展插件:
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());
}),
];
}
}