Help! Why the liquid tags are not working in .html() in javascript?!

Solved
Joiakim
Shopify Partner
24 1 0

Hello dear community, have any of you had this issue with liquid tags??

I have no idea how come it is possible but liquid tags are not working for me when I use .html() with jQuery in a javascript code. I am using a custom theme and I 've created a price table in html / liquid  that shows the price for each variant and works fine. Now I to give the option to show only the variant selected and for this I figured i would use javascript to replace the content of the price table with an 'onclick' event. 

But when trying to replace the content of the table, first attempt failed and I have no idea why: I see the html being rendered but the liquid tag such as {% for ....%} and {% if .... %} and even simple liquid objects such as {{ variant.price}} are absolutely not working!!!. Any idea why ? 
here is the piece of code that is not working , I shortened it for debugging purpose but this code works correctly in another theme when placed in a file named snippet-js-footer:

{% if product.available %}
			{{ 'option_selection.js' | shopify_asset_url | script_tag }}
<script>
				var selectCallback = function( variant, selector) {

if ( variant && variant.available ){
<----- This is when the code for the button goes ----> 
                        jQuery('#latest-sales-table').html('<thead><tr style="text-align:right"><th class="col-sm-2 col-xs-9">Marchand</th><th class="col-sm-2 col-xs-6">Prix/Taille</th><th class="col-sm-4 col-xs-1 info-list" >Info Release</th><th class="col-sm-3 col-xs-1">Lien</th></tr></thead><tbody id="body"><tr id="paid_shipping" class="paid"><td style="padding:0px!important;overflow:hidden;border:none"><div class= "shop-table_shop" >{{ variant.price }}{% for collection in product.collections %}{% assign collection_title = collection.title | downcase %}{% assign variant_option = variant.option2 | downcase %}{% if variant_option == collection_title %}{% assign product_collection = collection %}{% assign partner =  collection.metafields.custom_fields.partner.value  %}{% endif %}{% endfor %}{% unless product_collection == blank %}<div class="retailer_logo" style="overflow:none">helloworld<a href="{{product_collection.url}}"><img src="{{ product_collection.image.src | collection_img_url:'150x150', crop:'center', scale: 0 }}" alt="{{ product_collection.image.alt }}"></a></div>{% endunless %}</div></td></tr></tbody>');
                  } 
};
jQuery(document).ready(function($){
					new Shopify.OptionSelectors( "product-select",
					{
						product: {{ product | json }},
						onVariantSelected: selectCallback,
						enableHistoryState: true 
					});
				});p 

 

Accepted Solution (1)
Joiakim
Shopify Partner
24 1 0

This is an accepted solution.

I found the solution : I had to add the snippet inside the section for the liquid variables to work. 

As reference, the documentation on section in themes reads :  "Aside from global objects, variables created outside of sections aren't accessible within sections.

 

The section and block objects, as well as variables created within sections, aren't available outside of their respective section. The only exception is when you reference section and block objects within a snippet that's rendered inside the section you're referencing."

For anyone having issues with sections and how to insert them in template file : find the docs here 

Thank you for looking into it. All best

View solution in original post

Replies 12 (12)
Jason
Shopify Expert
11159 222 2274

I have lots of questions to help get some context (and to save guessing).

 

  • What type of file has this been added to? In other words is this a html liquid file or one that creates a js file?
  • And define not working - as in they are being skipped, you see an error, something else?
  • Do you have a link to the page that you can share?
★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★
Joiakim
Shopify Partner
24 1 0

Hi Jason!
This code has been added to a .liquid snippet file called 'snippet-js-footer', I am using an old theme which doesn't use sections. So all the important features using javascript and liquid  such as cart, variant selector, wishlist , image gallery and quickview belong in this file and they work fine. "<script></script>" tags have been added before and after each code.  

 

By not working I mean that the liquid reference have no effect : it seems they are been skipped. On the screenshot below, in the table - highlighted in yellow marker - where there should be an image, there is nothing.  I even tried placing a simple reference such as {{variant.price}} or {{product.title}}, ...nothing.  

Joiakim_2-1673874822175.png

 

 

I am trying this new feature on a backup of my current theme, to not mess up the live theme; but here is the link to the website: https://sneakerdrop.fr/collections/

 

 

Joiakim
Shopify Partner
24 1 0

@Jason I was able to reproduce the bug, by:

Step 1 - using {% render %}  to include the snippet in the theme file

Step 2 - using {% render %} to include the price table in the product file

Step 3 - reference the product file as a section in the  product template

 

I think that what is causing the problem is the {% section %} tag, when a section is referenced in the template ,  javascript in the rendered snippet has no effect. I was trying to use sections in a non-sectioned theme. 

 

Joiakim
Shopify Partner
24 1 0

This is an accepted solution.

I found the solution : I had to add the snippet inside the section for the liquid variables to work. 

As reference, the documentation on section in themes reads :  "Aside from global objects, variables created outside of sections aren't accessible within sections.

 

The section and block objects, as well as variables created within sections, aren't available outside of their respective section. The only exception is when you reference section and block objects within a snippet that's rendered inside the section you're referencing."

For anyone having issues with sections and how to insert them in template file : find the docs here 

Thank you for looking into it. All best

Erald
New Member
12 0 0

Hello @Joiakim !

Can you give an example because I also have the same problem?

Joiakim
Shopify Partner
24 1 0

Hello! 
Which problem are you having ? Using render tags in a section is not possible. 

Erald
New Member
12 0 0
I have built a file in the snippets directory, which also contains the js script. When I call this file to another file located in the sections directory, the js script does not work.
Joiakim
Shopify Partner
24 1 0

Well it's not going to work: you need to include any js code in between
{% javascript %} in the section file/ 

{% javascript %}
  javascript_code
{% endjavascript %}



Erald
New Member
12 0 0

Again this doesn't work. Can you see my code?

 

Joiakim
Shopify Partner
24 1 0
Sure post your section's code.
Erald
New Member
12 0 0

<script>

Shopify.Cart = Shopify.Cart || {};

Shopify.Cart.GiftWrap = {};

Shopify.Cart.GiftWrap.set = function() {
var headers = new Headers({ 'Content-Type': 'application/json' });

var request = {
method: 'POST',
headers: headers,
body: JSON.stringify({ updates: { {{ id }}: 1 }, attributes: { 'gift-wrapping': true } })
};
fetch('/cart/update.js', request)
.then(function() {
location.href = '/cart';
});
}

Shopify.Cart.GiftWrap.remove = function() {
var headers = new Headers({ 'Content-Type': 'application/json' });

var request = {
method: 'POST',
headers: headers,
body: JSON.stringify({ updates: { {{ id }}: 0 }, attributes: { 'gift-wrapping': '', 'gift-note': '' } })
};
fetch('/cart/update.js', request)
.then(function() {
location.href = '/cart';
});
}

// If we have nothing but gift-wrap items in the cart.
{% if cart.items.size == 1 and gift_wraps_in_cart > 0 %}
document.addEventListener("DOMContentLoaded", function(){
Shopify.Cart.GiftWrap.remove();
});
// If we have more than one gift-wrap item in the cart.
{% elsif gift_wraps_in_cart > 1 %}
document.addEventListener("DOMContentLoaded", function(){
Shopify.Cart.GiftWrap.set();
});
// If we have a gift-wrap item in the cart but our gift-wrapping cart attribute has not been set.
{% elsif gift_wraps_in_cart > 0 and cart.attributes.gift-wrapping == blank %}
document.addEventListener("DOMContentLoaded", function(){
Shopify.Cart.GiftWrap.set();
});
// If we have no gift-wrap item in the cart but our gift-wrapping cart attribute has been set.
{% elsif gift_wraps_in_cart == 0 and cart.attributes.gift-wrapping != blank %}
document.addEventListener("DOMContentLoaded", function(){
Shopify.Cart.GiftWrap.set();
});
{% endif %}

// When the gift-wrapping checkbox is checked or unchecked.
document.addEventListener("DOMContentLoaded", function(){
document.querySelector('[name="attributes[gift-wrapping]"]').addEventListener("change", function(event) {
if (event.target.checked) {
Shopify.Cart.GiftWrap.set();
} else {
Shopify.Cart.GiftWrap.remove();
}

});

document.querySelector('#gift-note').addEventListener("change", function(evt) {
var note = evt.target.value;
var headers = new Headers({ 'Content-Type': 'application/json' });

var request = {
method: 'POST',
headers: headers,
body: JSON.stringify({ attributes: { 'gift-note': note } })
};

fetch('/cart/update.js', request);
});
});

</script>  This is my script in the snippets file except for the rest of the code. 

{% render 'gift-wrapping' %} -> I called the snippets file in the sections file.

 

Joiakim
Shopify Partner
24 1 0

Hey Erald, 
First, you're adding this script in the wrong place. The functions you are calling cannot be triggered from a section itself. You'll have to add your snippet to your theme file or to your cart template. 

Then I noticed you've added attributes and variables which aren't assigned : 

gift_wraps_in_cart

and 

id

If the variables are assigned in your cart file then you should place the snippet in your cart template not in a section file. You might want to you review your cart template code for it to work properly. If you need further help on this I think you should open a new thread.