如何获取Shopware 6中自定义字段的标签?
获取Shopware 6自定义字段标签的实用方案
你提到的那份ADR文档核心是解决Storefront里自定义字段标签的高效加载问题,下面给你拆解实际可用的实现方式:
后端代码获取标签
自定义字段的标签存储在翻译表中,通过技术名称就能查到对应实体的翻译值。示例代码:
// 假设已拿到自定义字段技术名称 $technicalName $customField = $this->customFieldRepository->search( (new Criteria())->addFilter(new EqualsFilter('name', $technicalName)), $context )->first(); if ($customField) { // 获取当前上下文语言的标签 $label = $customField->getTranslation('label'); }
Storefront模板直接调用
在Twig模板里可以用官方提供的custom_field_label过滤器,直接传入技术名称即可:
{# 通用自定义字段标签 #} {{ 'your_custom_field_tech_name'|custom_field_label }} {# 关联到实体(比如产品)的自定义字段 #} {{ product.customFields.your_custom_field_tech_name|custom_field_label(product) }}
解析那份ADR的核心逻辑
那份文档讲的是Shopware优化自定义字段标签加载的方案,核心点:
- 后端通过
CustomFieldLoader服务按需加载当前页面需要的标签,避免一次性加载所有自定义字段造成冗余 - 前端通过Storefront扩展把标签注入模板变量,保证多语言环境下自动匹配当前语言
- 统一用过滤器调用,简化模板中的写法
如果是通过API获取标签,可以在请求时添加include=customFields.translations参数,或者自定义API扩展返回所需的标签字段。
内容的提问来源于stack exchange,提问作者Capt. Picard
相关产品推荐
相关产品推荐

