How to get a locale of a store in JavaScript?

kushagrapushowl
Tourist
5 0 1
We have an app that renders a widget on stores and has to show the price of the currently viewed product. The issue is that we show the price in wrong format as we don’t localize the price.
Here are some options I tried:
  1. There is a meta tag in the DOM which has a localized price. Eg. on an European store (comma means decimal) -> <meta property="og:price:amount" content="30,00"> . This was perfect solution until I realized that it always shows the product price, not the current variant price.
  2. There is a native JS function to get localized formatted currency, but that requires the locale. And we don’t have the locale info on the shopify store website.

Is there a way to the store's locale in JavaScript?

0 Likes
EphraimMulilo
Tourist
20 0 2

Have you tried using the 'Shopify.locale' variable? Try the cmd below in your store and see if it gives you the value you are looking for.

 

console.log(Shopify.locale)

 

 

0 Likes
kushagrapushowl
Tourist
5 0 1

@EphraimMulilo  I tried, but it only gives values like "en", "de" etc. Whereas any locale function in JavaScript or elsewhere accepts full locale as "en-US", "ar-EG" etc.

 

0 Likes
EphraimMulilo
Tourist
20 0 2

@kushagrapushowl Ah OK, I see. Yeah, I don't know any way to get that information. Hopefully, someone else in the community will be able to help you out.

0 Likes
ThemuMitch
Explorer
45 11 11

@kushagrapushowl,

 

Shopify provides resources that will format money according to a merchant's store currency.

 

First, the shop Liquid object has a property called money_format. Its output is £{{amount}} for GBP, ${{amount}} for USD, etc. 

https://shopify.dev/docs/themes/liquid/reference/objects/shop#shop-money_format

 

Second, check out @shopify/theme-currency on NPM. Installing this module exposes a JavaScript function, formatMoney, which accepts a price and a money format (which you've obtained from shop.money_format in Liquid) and outputs the correct, localised price.

https://www.npmjs.com/package/@shopify/theme-currency

 

Example usage

 

theme.liquid

<script>
  window.PLACEHOLDER.moneyFormat = {{ shop.money_format | json }};
</script>

 

Your .js file

import { formatMoney } from '@shopify/theme-currency'; // ES6 import may require Babel

formatMoney(price, window.PLACEHOLDER.moneyFormat);

 

I hope this helps.

Was your problem solved? Please mark this post as an Accepted Solution
0 Likes