为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
哆啦的时光机 2023-12-15 17:18:53
我正在尝试验证图像 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 }})我该如何解决这个问题?
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

你将 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 功能。


查看完整回答
反对 回复 2023-12-15
  • 1 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信