英文:
Shopware 6.5.0 : Get the current page ID using a event subscriber
问题
我想知道如何在事件监听器(如StorefrontRenderEvent或PageLoadedEvent)中检索当前加载的页面ID。或者,是否有另一种方法可以在Twig模板中获取加载页面的ID?我正在使用Shopware 6.5.0。
英文:
I would like to know how to retrieve the current loaded page ID in the event listener like StorefrontRenderEvent or PageLoadedEvent. Alternatively, is there another method to fetch the ID of the loaded page in the twig template? I am using Shopware 6.5.0.
答案1
得分: 1
通过编程方式,您可以[监听`CmsPageLoadedEvent`事件][1]。
```php
class MySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CmsPageLoadedEvent::class => 'onCmsPageLoaded',
];
}
public function onCmsPageLoaded(CmsPageLoadedEvent $event)
{
var_dump($event->getResult()->first()->getId());
}
}
在Twig模板中,您可以像这样获取cms_page
的ID:
{% set cmsPage = page.landingPage ? page.landingPage.cmsPage : page.cmsPage %}
{{ cmsPage.id }}
<details>
<summary>英文:</summary>
Programmatically you can [listen to the `CmsPageLoadedEvent`][1].
```php
class MySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CmsPageLoadedEvent::class => 'onCmsPageLoaded',
];
}
public function onProductsLoaded(CmsPageLoadedEvent $event)
{
var_dump($event->getResult()->first()->getId());
}
}
In the twig template you may get the id of cms_page
like this:
{% set cmsPage = page.landingPage ? page.landingPage.cmsPage : page.cmsPage %}
{{ cmsPage.id }}
答案2
得分: 0
关于商店页面,没有像“全局页面 ID” 这样的概念,因为页面的 ID 取决于加载的页面类型,例如,如果它是一个列表类别页面或产品详细信息页面。
根据您的实际用例,可能更好的方法是监听更具体的 \Shopware\Storefront\Page\Product\ProductPageLoadedEvent
或 \Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent
事件,因为它们分别提供对已呈现的 CmsPage 以及产品或类别的访问。
英文:
There is nothing like a "global page id" for storefront pages, as the id depends on the type of page that is being loaded, e.g. if it's a listing category page or a product detail page.
Depending on your actual use case it might be better to listen to the more specific \Shopware\Storefront\Page\Product\ProductPageLoadedEvent
or \Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent
events, as they give you access to the rendered CmsPage and product or category respectively.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论