12

I'm new to using Shopify Liquid, I'm having an issue with trying to use Liquid variables in JavaScript. I have put together an Instagram feed, which I want to use as a Section so that the UserId, ClientId, and accessToken can be easily added and changed from within the CMS, rather than in the code. The problem I've got is the Liquid variables aren't being picked up.

I've added data-settings for the three fields and then added the fields to the script with no effect. The feed works, but only if I manually add the IDs and token to the script and not through Liquid.

Any help with this would be great : )

{% if section.settings.insta_enable != blank %}

  {% if section.settings.insta_handle %}
  <div class="ss-handle">
    <h2>be social <a href="https://www.instagram.com/{{ section.settings.insta_handle }}" target="_blank">@{{ section.settings.insta_handle }}</a></h2>
  </div>
  {% endif %}

  <div data-section-id="{{ section.id }}" id="ss-instagram-feed" data-settings='{
  "user_id": {{ section.settings.user_id }},
  "client_id": {{ section.settings.client_id }},
  "access_token": "{{ section.settings.access_token }}"
  }'></div>

<!--
Note:
"user_id": {{ section.settings.instagram_id }}, // numeric (no quotes)
"access_token": "{{ section.settings.instagram_access_token }}", // string in quotes
-->

{% endif %}


{% schema %}
  {
    "name": "Instagram Feed",
    "settings": [
      {
        "type": "header",
        "content": "Feed Configuration"
      },
      {
        "label": "Enable Instagram feed",
        "id": "insta_enable",
        "type": "checkbox"
      },
      {
        "label": "User ID",
        "id": "user_id",
        "type": "text"
      },
      {
        "label": "Client ID",
        "id": "client_id",
        "type": "text"
      },
      {
        "label": "Access Token",
        "id": "access_token",
        "type": "text"
      },
      {
        "label": "Insta Handle (enter without @ symbol)",
        "id": "insta_handle",
        "type": "text"
      }
    ],
    "presets": [
      {
        "name": "Instagram Feed",
        "category": "Image"
      }
    ]
  }
{% endschema %}

{% javascript %}
//<script>

function instafeed_load() {

  // JS goes here
  $(document).ready(function() {

    var settings = $('#ss-instagram-feed').data('settings');

    var feed = new Instafeed({
        clientId: 'settings.client_id', 
        accessToken: 'settings.access_token',
        get: 'user',
        userId: settings.user_id,,
        target: 'ss-instagram-feed',
        limit: 5,
        resolution: 'standard_resolution',
        template: '<li><a class="instagram-image" href="{{link}}" target="_blank"><img src="{{image}}"/></a></li>'
    });
    feed.run();

  });

  $(window).on('load', function() {
    setTimeout(function() {
      $('body, #ss-instagram-feed, h1, h3').addClass('loaded');
    }, 500);
  });

}
function instafeed_unload() {
  // you will want to do clean-up and/or destroy what you created in instafeed_load
}
function instafeed_event_handler(event) {
  // there are cleaner ways to write this, but the below works for me
  if (event.detail.sectionId == '1533732475847') { // 1533732475847 or insta-feed
    if (event.type == 'shopify:section:load') {
      instafeed_load();
    } else if (event.type == 'shopify:section:unload') {
      instafeed_unload();
    }
  }
}

$(document).on('shopify:section:load shopify:section:unload', instafeed_event_handler);
$(document).ready(function() {
  instafeed_load(); // this is to execute on initial page load
});

//</script>
{% endjavascript %}

1
  • can you share the url of your page ? This script seems to work fine.. Commented Aug 10, 2018 at 11:38

4 Answers 4

12

You can do something like that:

<script>
var myVar = {{yourLiquidVar | json}}
</script>

That instruction will convert your liquid var into json format

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the example, but i've already tried it and it throws up the following error "Uncaught SyntaxError: Unexpected token {"
i've now managed to get the code working using the following example <input type="hidden" name="" id="insta-clientid" value="{{ section.settings.client_id }}" /> clientId : $('#insta-clientid').val(), Is there any negatives to this approach?
if my variable yourLiquidVar is array, is that working?
5

you can use liquid variable for js in single quotes.

Here is an example:

{% assign test = 0 %}

// calling liquid variable in js

var testval= '{​{ test }}';

If a liquid var is an object, then you can use:

var productJSON = {{ product | json }};

3 Comments

if product is an array then we can't pass it as a json, right?
You can use window.productJSON = {{ product | json }}; This will convert your array into JSON.
Can I assign Javascript variable to Liquid variable otherwise?
3

For JS you can use something like:

var contactId = "{{user.id}}";

You need to set quotes like if it was a string.

1 Comment

This returns a syntax error for me when used within a .liquid file and inside script tags. Meanwhile, var myVar = {{yourLiquidVar | json}} works.
0

{% assign test = 0 %}

you can use it like this

var testval= {​{test | json}};

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
if test is an array then we can't pass it as a json, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.