How to get app block setting from its javascript asset file

Solved

How to get app block setting from its javascript asset file

EddieLuong
Shopify Partner
39 1 21

Hi guys,

I create an app block (using theme app extension) with the file/folder structure:

themes-app-extension

-- assets

    ---- my-css.css

    ---- my-javascript.js

-- blocks

    ---- app-block.liquid

-- locales

-- snippets

 

In the app-block.liquid I create the block setting in the block schema as below:

 

{% schema %}
  {
    "name": "My block",
    "target": "section",
    "stylesheet": "my-css.css",
    "javascript": "my-javascript.js",
    "templates": [
      "collection", "index"
    ],
    "settings": [
      {
        "id": "text_size",
        "type": "number",
        "label": "Text size",
        "default": 15
      }, {
        "id": "icon_size",
        "type": "number",
        "label": "Icon size",
        "default": 20
      }
    ]
  }
{% endschema %}

 

In app-block.liquid, I can get the app block setting by access the block object as below:

 

{{ block.settings.text_size }}
{{ block.settings.icon_size }}

 

But now I want to get the app block setting in javascript file, meaning my-javascript.js

Is there anyway to do this? I appreciate any help and suggestion.

Thanks

Accepted Solution (1)

scottshop
Shopify Partner
9 1 1

This is an accepted solution.

@EddieLuong did you find an answer for this? I believ you'd want to write to a JS variable within your liquid template and then read that value from within your my-javascript.js file.

View solution in original post

Replies 4 (4)

scottshop
Shopify Partner
9 1 1

This is an accepted solution.

@EddieLuong did you find an answer for this? I believ you'd want to write to a JS variable within your liquid template and then read that value from within your my-javascript.js file.

EddieLuong
Shopify Partner
39 1 21

Hi @scottshop Yes, I did like that and it's working fine.

Thanks

raul-vila
Shopify Partner
5 1 1

Hi there, could you write an example of how did you do it? Thanks 🙂

ShaunStarttin
Shopify Partner
12 2 2

The easiest way seems to be defining a global variable on `window` in your liquid file and reading it in JS assets. You could also have a top-level unique name to avoid collisions and wrap a bunch of variables. Your liquid block:

 

 

<script>
window.MY_APP_NAME = { customerId: "{{customer.id}}" }
</script>

 

 

Alternately, a Shopify demo uses html attributes and reads them from the DOM (liquid block and js asset). This seems useful to find specific pieces of data in the DOM structure (e.g. loop over all products).