如何在 Shopify Liquid 模板中正确显示 ACF 元字段中的 JSON 数组值?

问题描述 投票:0回答:1

我在我的测试网站(我用于网站开发)上使用 ACF 插件来添加为产品选择服装尺寸的功能。但是,即使我正在遵循文档,我目前也无法显示此数据。你能建议一下可能有什么问题吗?

主题:黎明13.0.1 文件:主产品.液体

    <h2>ACF 'oval' Metafield Debug</h2>
    <p><strong>Raw JSON Value:</strong> {{ product.metafields.custom.oval }}</p>
    {% assign oval_array = product.metafields.custom.oval | parse_json %}
    <p><strong>Parsed Array:</strong> {{ oval_array | join: ', ' }}</p>

    <h3>Iterating Over 'oval' Array</h3>
    {% if oval_array.size > 0 %}
    <ul>
    {% for item in oval_array %}
    <li>{{ item }}</li>
    {% endfor %}
    </ul>
    {% else %}
    <p>Error: JSON is not parsed correctly.</p>
    {% endif %}

    {% if product.metafields.custom.oval %}
    <ul>
    {% for item in product.metafields.custom.oval %}
    <li>{{ item }}</li>
    {% endfor %}
    </ul>
    {% else %}
    <p>No items found in 'oval'.</p>
    {% endif %}

    Result:

    <h2>ACF 'oval' Metafield Debug</h2>
    <p><strong>Raw JSON Value:</strong> "["1","2","3"]"</p>
    <p><strong>Parsed Array:</strong> "["1","2","3"]"</p>
    <h3>Iterating Over 'oval' Array</h3>
    <p>Error: JSON is not parsed correctly.</p>
    <ul></ul>

[Result](https://i.stack.imgur.com/CiQRu.png)
[Settings](https://i.stack.imgur.com/kEZLM.png)
[Settings](https://i.stack.imgur.com/OBrpg.png)
[Settings](https://i.stack.imgur.com/WeGDq.png)
javascript shopify liquid
1个回答
0
投票

问题似乎在于您从元字段接收的 JSON 字符串的格式。

直接输出: 不要使用 Liquid 的 {{

product.metafields.custom.oval
}} 来输出值,而是尝试直接输出值而不用 Liquid 解释它。例如:

<p><strong>Raw JSON Value:</strong> {{ product.metafields.custom.oval | json }}</p>

自定义解析:如果直接输出不起作用,您可能需要手动解析JSON字符串以删除多余的引号。具体方法如下:

{% assign oval_json = product.metafields.custom.oval %}
{% assign oval_array = oval_json | replace: '"', '' | parse_json %}
© www.soinside.com 2019 - 2024. All rights reserved.