【问题标题】:Liquid nesting variable output into a variable name液体嵌套变量输出成变量名
【发布时间】:2021-04-22 14:14:37
【问题描述】:

我在 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

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

【问题讨论】:

    标签: shopify liquid


    【解决方案1】:

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

    <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>
    

    【讨论】:

    • 谢谢@cMarius,但这不起作用。它不会在变量中输入变量[field_first]。这是输出:ID: 02-aktivitaetsspielzeug - Value: false normal way: Achtung: Nicht für Kinder unter drei Jahren geeignet. nest the variable output: translation missing: de.products.productwarnings.field[field_first]
    【解决方案2】:

    在使用 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>
    

    【讨论】:

    • 谢谢,@dave B,这很有魅力!正是我需要的!非常感谢!
    • 太棒了!很高兴为您提供帮助!
    • 我在下一个问题中遇到了关于 true is not truthy 的问题。也许有些人也可以在这里帮助我?我现在真的很沮丧,因为一个如此简单的错误......stackoverflow.com/questions/67417528/…
    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2011-11-07
    • 2011-03-29
    相关资源
    最近更新 更多