0

I need to get the locale code of the current store ( something like en_EN ) in javascript

but I only know the store id :

let storeId = window.checkout.storeId;

1 Answer 1

0

I found a way to add the locale code in the window object in javascript. For me the best is to add it in the window.checkout object (since there's already some information about the store) so i made a plugin of the Magento\Checkout\Block\Cart\Sidebar class.

// path: app/code/<vendor>Checkout/Plugin/Block/Cart/Sidebar.php
<?php

namespace <vendor>\Checkout\Plugin\Block\Cart;

use Magento\Checkout\Block\Cart\Sidebar as DefaultSidebar;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Sidebar
{
    protected ScopeConfigInterface $scopeConfig;

    public function __construct(
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * {@inheritdoc}
     * add the `localeCode` variable in the result array
     */
    public function afterGetConfig(DefaultSidebar $subject, $result)
    {
        $storeId = $result['storeId'];
        $localeCode = $this->scopeConfig->getValue(
            'general/locale/code',
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        $result['localeCode'] = $localeCode;
        return $result;
    }
}
<!-- path: app/code/<vendor>/Checkout/etc/di.xml--> 
<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!--  ... -->
    <type name="Magento\Checkout\Block\Cart\Sidebar">
        <plugin name="<vendor>_checkout_plugin_block_cart_sidebar"
                type="<vendor>\Checkout\Plugin\Block\Cart\Sidebar" />
    </type>

</config>

With this plugin I can now get the localeCode like this :

window.checkout.localeCode

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.