[英]Getting the page variable to Sonata twig templates
使用奏鳴曲模板時,PageBundle 中的各個頁面旨在擴展 page.site.layout 模板,然后您可以使用 twig 標准塊系統來放置您喜歡的東西。 但是我發現頁面變量在我的頁面上未定義,我試圖了解頁面變量如何到達它們。
我在多個模板中使用了 var_dump 的頁面變量,但找不到它在哪里,我試過谷歌搜索,但沒有找到任何感興趣的東西。
{% extends page.site.layout %}
我希望默認情況下在每個奏鳴曲頁面中都可以使用頁面變量,我不確定是否需要從奏鳴曲傳入頁面,我有點認為它是由奏鳴曲處理的?
希望這會有所幫助,這是我如何做到的。
頁面幫助服務:
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());
}),
];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.