将 javascript 函数输出分配给 Liquid 变量

我正在尝试验证图像 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 }})


我该如何解决这个问题?


哆啦的时光机
浏览 67回答 1
1回答

largeQ

你将 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将在之后运行它的代码。所以你不能在 Liquid 中使用 javascript 功能。
打开App,查看更多内容
随时随地看视频慕课网APP