液体嵌套变量输出到变量名

Liquid nesting variable output into a variable name

我的 Shopify 商店中遇到以下挑战。

我正在使用 ACF(高级自定义字段),如果我想使用它,我在前端使用此代码: {{product.metafields.warnhinweise.not-under-three-years}} 输出为:true

现在我想从翻译文件 (locals/de.json) 输出一个变量,要访问这个变量我必须使用:{{ 'products.productwarnings.not-under-three-years' | t }}

我想要完成的事情和我目前挣扎的地方是:如何将自定义字段中的 ID 作为翻译变量中的变量名传递?

我尝试了以下方法:

<p>Example: {{ product.metafields.warnhinweise.not-under-three-years }}</p>
<ul>
  {% for field in product.metafields.warnhinweise %}
  <li>ID: {{ field | first }} - Value: {{ field | last }}</li>
    <ul>
      <li>normal way: {{ 'products.productwarnings.not-under-three-years' | t }}</li>
      <li>nest the variable output: {{ 'products.productwarnings.{{field | first}}'  | t }}</li>
    </ul>
  {% endfor %}
</ul>

但显然,这是行不通的。我怎么能完成插入 {{field |首先}}进入我的翻译变量?

以上代码的输出如下:

Example: true

 - ID: not-under-three-years - Value: true
   - normal way: Achtung: Nicht für Kinder unter drei Jahren geeignet.
   - nest the variable output: translation missing: de.products.productwarnings.field | first

另外,我从 liquid 中收到语法错误:[dev-henry] (sections/product-template.liquid) Liquid syntax error (line 220): Unexpected character ' in "{{ 'products.productwarnings.field | first | t }}"

您可以尝试动态提供该对象键名,如下所示:

<p>Example: {{ product.metafields.warnhinweise.not-under-three-years }}</p>
<ul>
  {% for field in product.metafields.warnhinweise %}
  {% assign field_first = field | first %}
  <li>ID: {{ field_first }} - Value: {{ field | last }}</li>
    <ul>
      <li>normal way: {{ 'products.productwarnings.not-under-three-years' | t }}</li>
      <li>nest the variable output: {{ 'products.productwarnings[field_first]' | t }}</li>
    </ul>
  {% endfor %}
</ul>

使用 Liquid 模板语言时的一个常见误解是尝试在 Liquid 命令中使用 运行 Liquid 命令:

{{ 'products.productwarnings.{{field | first}}' | t }} <!-- Illegal nesting, won't work -->

此语法无效,充其量会导致解析器在您的语言文件中查找字面上名为“{{field | first}}”的翻译键

但是,您的方向是正确的。我们需要的是一个包含我们要使用的语言变量全名的字符串,然后将其提供给翻译过滤器。我们只需要将其分解为一些更明确的步骤:

{% assign field_first = field | first %}
{% assign language_key = 'products.productwarnings.' | append: field_first %}
<h2>{{ language_key | t }}</h2>