【问题标题】:Liquid variable holds metafield path but does not work in img srcLiquid 变量保存元字段路径,但在 img src 中不起作用
【发布时间】:2021-12-15 23:14:03
【问题描述】:

我需要在 Shopify 的元字段中显示作为 URL 的四个随机图像之一,因此必须使用变量作为 img src。

{%- assign min = 1 -%}
{%- assign max = 4 -%}
{%- assign diff = max | minus: min -%}
{%- assign random_number = "now" | date: "%N" | modulo: diff | plus: min -%}

{% capture image %}
pages["explore-more-ingredients"].metafields.global.explore_ingredients_image{{ random_number}}.value
{% endcapture %}

因此,我使用该图像变量并查看以下各项在浏览器中的显示方式(附图片)

1. {{ image }} <br>
2. {{ pages["explore-more-ingredients"].metafields.global.explore_ingredients_image2.value }} <br>
3. <img src="{{ image }}">
4. <img src="{{ pages["explore-more-ingredients"].metafields.global.explore_ingredients_image2.value }}">

我做错了什么?由于 URL 是随机生成的,因此需要 3 号才能工作。这是语法问题吗?

当我查看如何在浏览器中呈现 3 的源代码时,它显示 &lt;img src="pages[" explore-more-ingredients"].metafields.global.explore_ingredients_image3.value"=""&gt;

感谢您的指导。

【问题讨论】:

  • 我有另一个解决这里语法错误的答案:stackoverflow.com/questions/70293919/… 简而言之,在使用 Liquid 时,我们从不将模板括号嵌套在模板括号内。你应该只需要assign 你的元字段键到一个变量,然后使用方括号表示法访问它。 :)

标签: shopify liquid


【解决方案1】:

生成一个包含所有图片的数组。

在所有图片的边界内生成随机数

显示带有随机数的图片。

{% assign images= pages["explore-more-ingredients"].metafields.global.explore_ingredients_image2.value | append: " | " | append: image2 | append: " | " | append: image3 | split: " | " %}

{% assign min = 0 %}
{% assign max = images | size %}
{% assign diff = max | minus: min %}
{% assign randomNumber = "now" | date: "%N" | modulo: diff | plus: min %}

<img src="{{images[randomNumber]}}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2021-02-12
    • 2011-01-02
    • 2014-01-20
    • 2021-09-29
    • 1970-01-01
    • 2011-12-30
    • 2015-04-06
    相关资源
    最近更新 更多