如果图像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 }})
我该怎么解决这个问题?
发布于 2020-09-05 23:06:28
你是混合JS和液体,这是可以的,如果你只是通过液体含量。
目前,液态代码如下所示:
{% capture png_exists %}<script>imageExists({{ img_png }})</script>{% endcapture %}
png_exists => <script>imageExists(http://asset_img_url.jpg)</script>
您不能执行Javascript代码,并且期望finish知道它,Javascript是在液体之后执行的,所以液态完成它的逻辑,Javascript之后会运行它的代码。
所以你不能在液体中使用javascript功能。
https://stackoverflow.com/questions/63761484
复制