Shopware 6插件:搜索结果分页SEO友好URL生成问题
Shopware 6搜索结果分页SEO友好URL生成异常问题
我在Shopware 6中实现搜索结果分页时,遇到了SEO友好URL生成异常的问题。自定义Twig模板继承自storefront的pagination.html.twig,这套代码在分类页面生成SEO URL完全正常,但从搜索结果页第1页导航到第2页时就出问题。
问题大概率出在seoParams的修改逻辑,以及搜索结果页currentNavigationId的处理上。以下是简化后的代码:
{# Extend the 'pagination.html.twig' template from the storefront #} {% sw_extends '@Storefront/storefront/component/pagination.html.twig' %} {# Define the 'component_pagination' block #} {% block component_pagination %} {# Loop through each page #} {% for i in 1..totalPages %} {# Set up an empty SEO parameters object #} {% set seoParams = {} %} {# Retrieve and modify query parameters #} {% set seoParams = context.context.extensions.tanmarNgSeoPagination.queryParameters %} {# Check if the current page is not equal to the current iteration #} {% if i != currentPage %} {% if currentPage %} {% set seoParams = seoParams|merge({ p: i }) %} {% endif %} {# Properly encode the SEO parameters into a string before using it #} {% set seoParams = '?' ~ seoParams|url_encode %} {# Check if currentNavigationId is defined and generate SEO-friendly URL #} {% if currentNavigationId is defined %} {{ dump(seoParams) }} <a href="{{ seoUrl('frontend.navigation.page', { navigationId: currentNavigationId }) ~ seoParams }}"></a> {% endif %} {% endif %} {% endfor %} {# Call the parent pagination block #} {{ parent() }} {% endblock %}
我已经检查过URL编码、seoUrl函数以及整体逻辑,但还是找不到问题原因。另外发现一个现象:搜索时浏览器地址会从http://localhost/Clothing/Men/变成http://localhost/search?search=new,原来的/Clothing/Men/路径被移除了。求解决思路或建议。
问题原因与解决方案
路由匹配错误
你当前的代码始终用frontend.navigation.page路由生成URL,这个路由只适用于分类页面。搜索结果页对应的路由是frontend.search.page,共用一套分页模板时,必须区分当前页面的路由类型。currentNavigationId在搜索页无意义
搜索结果页不属于任何分类,currentNavigationId在这里没有实际作用,强行使用会导致URL生成逻辑混乱,这也是搜索时路径被移除的核心原因。修正后的代码逻辑
修改模板,判断当前页面的路由,分别调用对应路由生成SEO URL:
{% sw_extends '@Storefront/storefront/component/pagination.html.twig' %} {% block component_pagination %} {% for i in 1..totalPages %} {% if i != currentPage %} {# 初始化参数,保留原有查询参数并合并分页参数 #} {% set seoParams = context.context.extensions.tanmarNgSeoPagination.queryParameters|merge({ p: i }) %} {% set seoUrlPath = '' %} {# 判断当前路由类型,选择对应SEO路由 #} {% if app.request.attributes.get('_route') == 'frontend.search.page' %} {% set seoUrlPath = seoUrl('frontend.search.page', { search: app.request.query.get('search') }) %} {% elseif currentNavigationId is defined %} {% set seoUrlPath = seoUrl('frontend.navigation.page', { navigationId: currentNavigationId }) %} {% endif %} {# 拼接参数并生成链接 #} {% if seoUrlPath %} {% set fullUrl = seoUrlPath ~ '?' ~ seoParams|url_encode %} <a href="{{ fullUrl }}">{{ i }}</a> {% endif %} {% else %} <span class="current-page">{{ i }}</span> {% endif %} {% endfor %} {{ parent() }} {% endblock %}
- 额外优化点
- 直接合并分页参数到原有查询参数中,避免重复初始化
seoParams - 通过
app.request.attributes.get('_route')准确判断当前页面路由类型 - 搜索页保留
search参数,确保分页后搜索关键词不丢失
- 直接合并分页参数到原有查询参数中,避免重复初始化
内容的提问来源于stack exchange,提问作者mlodhi
相关产品推荐
相关产品推荐

