我正在嘗試驗證圖像 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條經驗 獲得超8個贊
你將 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 功能。
- 1 回答
- 0 關注
- 231 瀏覽
添加回答
舉報
0/150
提交
取消