Using javascript variables in Shopify liquid

2019-08-18 00:42发布

问题:

I am trying to use a javascript variable inside the image tag but it is not working.

I want to create a filter for my collection in a developing project, where I can filter products by the textures of products. I have coded the following:

<div class="collection-filter-navbar-nav">
{% assign tags = 'white, yellow, golden' | split: ',' %}
<ul class="fabric-filter">
<li><a href="javascript:void(0);" >All</a></li>
 {% for t in tags %}
{% assign tag = t | strip %}
{% if current_tags contains tag %}
<li><a href="javascript:void(0);" data-value="{{ tag | handle }}" >{{ tag }}</a></li>
{% elsif collection.all_tags contains tag %}
<li><a href="javascript:void(0);" class="filter-lists" data-value="{{ tag | handle }}">{{ tag }}</a></li>
{% endif %}
{% endfor %}
</ul>
</div>

The html is showing in the front end, but what I need, I want to add a texture image in each tag in reference to the tag name.

So I scripted :

jQuery(document).ready(function(){
 var filter_tabs = jQuery('.fabric-filter > li > a.filter-lists');
  jQuery.each( filter_tabs, function(index, element){
    var data_value = jQuery(this).data('value');
    {% assign value = data_value %}
    var img_append = '<img src="{{ 'f1-'+value+'.png'  | asset_url }}">'
  jQuery(img_append).appendTo(jQuery(this));
   console.log(data_value);
   });
  });

But it is showing error. I know this can be done by css, but I am using javascript just for dynamism.

回答1:

You won't be able to do this as the liquid code all runs before the jquery code.

By the time you are running the jquery liquid has already outputted the line {% assign value = data_value %}