问题描述
我正在尝试验证图像URL(如果存在于javascript中)。因此,我将此代码添加到接受网址的javascript中,并返回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}})
我该如何解决?
解决方法
您正在将JS与Liquid混合匹配,如果您仅传递液体含量,则可以。
此刻,液体看起来像这样:
{% capture png_exists %}<script>imageExists({{ img_png }})</script>{% endcapture %}
png_exists => <script>imageExists(http://asset_img_url.jpg)</script>
您不能执行Javascript代码并期望液体知道它,Javascript是在液体之后执行的,因此,液体完成是其逻辑,Javascript随后将运行其代码。
因此,您不能在液体中使用javascript功能。