首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从Shopware 6中的类别实体获取类别URL?

在 Shopware 6 中,从类别实体获取类别 URL 通常涉及到使用 Shopware 的 API 或者服务来生成类别的 SEO URL。以下是一些常见的方法来实现这一目标:

方法一:使用 SeoUrlGenerator 服务

SeoUrlGenerator 服务可以用来生成实体的 SEO URL。你可以通过依赖注入来使用这个服务。

示例代码

代码语言:javascript
复制
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Routing\RouterInterface;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Framework\Seo\SeoUrlGenerator;

class CategoryUrlService
{
    private $seoUrlGenerator;
    private $router;

    public function __construct(SeoUrlGenerator $seoUrlGenerator, RouterInterface $router)
    {
        $this->seoUrlGenerator = $seoUrlGenerator;
        $this->router = $router;
    }

    public function getCategoryUrl(CategoryEntity $category, SalesChannelContext $context): string
    {
        $seoUrl = $this->seoUrlGenerator->generate(
            'frontend.navigation.page',
            ['navigationId' => $category->getId()],
            $context->getContext()
        );

        return $this->router->generate('frontend.navigation.page', ['navigationId' => $category->getId()]);
    }
}

方法二:使用 SeoUrlRepository

你也可以直接从 SeoUrlRepository 中获取类别的 SEO URL。

示例代码

代码语言:javascript
复制
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

class CategoryUrlService
{
    private $seoUrlRepository;

    public function __construct(EntityRepositoryInterface $seoUrlRepository)
    {
        $this->seoUrlRepository = $seoUrlRepository;
    }

    public function getCategoryUrl(CategoryEntity $category, Context $context): ?string
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('foreignKey', $category->getId()));
        $criteria->addFilter(new EqualsFilter('routeName', 'frontend.navigation.page'));
        $criteria->addFilter(new EqualsFilter('isCanonical', true));

        $seoUrls = $this->seoUrlRepository->search($criteria, $context);

        if ($seoUrls->count() === 0) {
            return null;
        }

        return $seoUrls->first()->getSeoPathInfo();
    }
}

方法三:使用 Twig 模板

如果你在 Twig 模板中需要获取类别 URL,可以使用 path 函数。

示例代码

代码语言:javascript
复制
{% set categoryUrl = path('frontend.navigation.page', { navigationId: category.id }) %}
<a href="{{ categoryUrl }}">{{ category.name }}</a>

总结

  1. 使用 SeoUrlGenerator 服务:通过依赖注入使用 SeoUrlGenerator 服务来生成类别的 SEO URL。
  2. 使用 SeoUrlRepository:直接从 SeoUrlRepository 中获取类别的 SEO URL。
  3. 使用 Twig 模板:在 Twig 模板中使用 path 函数生成类别 URL。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券