如何根据用户国家代码输出数组中对应的name、value字段值
实现方案
你可以通过「拼接目标字段名+数组查找」的方式实现动态匹配,不需要写死数组下标,适配所有国家代码场景,具体实现如下:
方案1:使用模板内置查找函数(推荐)
如果你的模板环境支持find辅助函数(绝大多数电商平台模板如BigCommerce Stencil、Shopify Liquid均支持),可以直接用以下代码:
{{!-- 拼接要匹配的目标自定义字段名 --}} {{assign "target_field_name" (concat "TRS_TITLE_" settings.country_code)}} {{!-- 在自定义字段数组中查找name匹配的项 --}} {{assign "matched_field" (find product.custom_fields "name" target_field_name)}} {{#if matched_field}} <h1>{{matched_field.value}}</h1> {{!-- 如需输出字段名可直接调用 {{matched_field.name}} --}} {{else}} <h1>It's not there</h1> {{/if}}
方案2:遍历匹配(兼容性更强)
如果模板没有内置查找函数,可以用遍历的方式逐个匹配,兼容所有模板环境:
{{assign "target_field_name" (concat "TRS_TITLE_" settings.country_code)}} {{assign "matched_field" null}} {{#each product.custom_fields}} {{#if (eq this.name target_field_name)}} {{assign "matched_field" this}} {{/if}} {{/each}} {{#if matched_field}} <h1>{{matched_field.value}}</h1> {{else}} <h1>It's not there</h1> {{/if}}
原写法问题说明
你之前固定取下标2的写法依赖数组的固定顺序,一旦后台调整了自定义字段的排序、新增了其他国家的字段,就会出现匹配错误。动态匹配name字段的方案不受数组顺序影响,稳定性更高。
内容的提问来源于stack exchange,提问作者nipulse
相关产品推荐
相关产品推荐

