Shopware 6.5.0:使用事件订阅器获取当前页面ID。

huangapple go评论58阅读模式
英文:

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 =&gt; &#39;onCmsPageLoaded&#39;,
        ];
    }

    public function onProductsLoaded(CmsPageLoadedEvent $event)
    {
        var_dump($event-&gt;getResult()-&gt;first()-&gt;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.

huangapple
  • 本文由 发表于 2023年6月22日 15:18:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定