【问题标题】:Assign javascript function output to liquid variable将javascript函数输出分配给液体变量
【发布时间】:2020-09-06 06:45:44
【问题描述】:

我正在尝试验证图像 URL 是否存在于 javascript 中。所以我在 javascript 中添加了这段代码,它接受一个 URL 并返回 http 状态代码。

function imageExists(image_url){
    var http = new XMLHttpRequest();
    http.open('HEAD', image_url, false);
    http.send();
    return http.status != 404;
}

在液体模板中,我想在显示之前检查图像 URL 是否存在

<div class="variant-cat-attributes">
  {% assign tags = product.metafields.product_meta.tag | split: "," %}
  {% for tag in tags %}
      <div class="item">
      {% capture tag_slug %}{{ tag | replace: " ", "_"}}{% endcapture %}
      {% assign img_png = 'tag' | append: '-' | append: tag_slug | append: '.png'%}
      {% capture png_exists %}<script>imageExists({{ img_png }})</script>{% endcapture %}
      {% if png_exists%}
        <img src="{{ img_png | file_img_url: '32x32' }}" />
      {% else %}
        {% assign img_jpg = 'tag' | append: '-' | append: tag_slug | append: '.jpg'%}
        {% capture jpg_exists %}<script>imageExists({{ img_jpg }})</script>{% endcapture %}
        {% if jpg_exists%}
          <img src="{{ img_png | file_img_url: '32x32' }}" />
        {% else %}
          {% assign img_default = 'tag' | append: '-' | append: 'default' | append: '.png'%}
          <img src="{{ img_default | file_img_url: '32x32' }}" />
        {% endif %}
      {% endif %}
      <p class="item-name">{{ tag | capitalize }}</p></div>
 {% endfor %}
</div>

我刚刚开始了解液体,所以我不知道这种方式是否正确。但是这段代码发生的情况是脚本标签被当作一个字符串,并且其中的代码没有运行

png_exists = imageExists({{ img_png }})

我该如何解决这个问题?

【问题讨论】:

    标签: javascript php shopify liquid


    【解决方案1】:

    你是混合匹配JS和Liquid,如果你只传递液体内容就可以了。

    目前液体看到你的代码是这样的:

    {% capture png_exists %}<script>imageExists({{ img_png }})</script>{% endcapture %}
    
    png_exists => <script>imageExists(http://asset_img_url.jpg)</script>
    

    你不能执行 Javascript 代码并期望 Liquid 知道它,Javascript 是在 Liquid 之后执行的,所以 Liquid 完成它的逻辑并且 Javascript 将在之后运行它的代码。

    所以你不能在液体中使用 javascript 功能。

    【讨论】:

    • 我知道。我想知道我该如何解决?如何编辑代码使 js 不在液体中?
    • @SaeeshTendulkar 您可以使用带有错误状态的图像标签&lt;img src="{{img_png | asset_url }}" onError="style.display = 'none';"&gt; 没有简单的方法来检查资产是否存在流动性。
    • 那行不通。如果图像不存在,我需要显示默认图像,并在此之前检查 jpg 图像。
    • @SaeeshTendulkar 你可以根据上面的错误状态使用 Javascript 逻辑来做到这一点。您将只有两个图像并根据错误状态是否触发而显示其中一个,还有其他 JS 方法。我认为这很简单。
    • 这就是我需要的。关于如何修复它的方法。您可以发布一个作为答案吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多