PARSING LIQUID TO JAVASCRIPT

Solved
tobitobin
New Member
4 0 0
Attempting to parse a url string from a tag, meta_Image:<url> to a js variable so that I may inject it into a container class on an app that I am using. Everything I attempt returns null or undefined.
 
{% for tag in product.tags %}
{% if tag contains "meta_Image" %}
{% assign url = tag | split:"meta_Image:" | last %}
{% if url %}
<script>console.log("yes")</script>
{%endif%}
<script>
$(document).ready(function(){
var m_Image = {{ url }};
var imageContainer = $(".rondell-container");
imageContainer.css('background-image','{{m_Image}}');
console.log("this is the:" + m_Image);
console.log("success")
});
</script>
{% endif %}
{% endfor %}
0 Likes
ThemuMitch
Explorer
45 11 11

This is an accepted solution.

Hi tobitobin,

 

It seems to me like your logic is correct, but I noticed the following:

  1. You haven't defined jQuery in this inline script, so I'd replace the jQuery bits with vanilla JavaScript.
  2. You're missing quotes around the {{ url }} which will cause an error.
  3. You're trying to use m_Image as a Liquid variable, but it's actually a JavaScript variable.

I think the below code should work, or at least come close to what you need. I've wrapped it in an IIFE to isolate the variables created.

{% for tag in product.tags %}
  {% if tag contains 'meta_Image' %}
    {% assign url = tag | split: 'meta_Image:' | last %}
    <script>
      (function() {
        var m_Image = "{{ url }}";
        var imageContainer = document.querySelector('.rondell-container');
        imageContainer.style.backgroundImage = m_Image;
      })();
    </script>
  {% endif %}
{% endfor %}

 

I hope this helps.

Was your problem solved? Please mark this post as an Accepted Solution
0 Likes
tobitobin
New Member
4 0 0
This is great, it is whittling down errors.
The issue is that, inside the
0 Likes