在 Shopware 6 中,从类别实体获取类别 URL 通常涉及到使用 Shopware 的 API 或者服务来生成类别的 SEO URL。以下是一些常见的方法来实现这一目标:
SeoUrlGenerator
服务SeoUrlGenerator
服务可以用来生成实体的 SEO URL。你可以通过依赖注入来使用这个服务。
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。
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 模板中需要获取类别 URL,可以使用 path
函数。
{% set categoryUrl = path('frontend.navigation.page', { navigationId: category.id }) %}
<a href="{{ categoryUrl }}">{{ category.name }}</a>
SeoUrlGenerator
服务:通过依赖注入使用 SeoUrlGenerator
服务来生成类别的 SEO URL。SeoUrlRepository
:直接从 SeoUrlRepository
中获取类别的 SEO URL。path
函数生成类别 URL。领取专属 10元无门槛券
手把手带您无忧上云