3

I need to get current store view code in JS component to compose i18n-compatible route to the REST API operation:

define(
    ["jquery", "ko", "uiComponent", "mage/translate"],
    function ($, ko, Component, translate) {
        "use strict"

        const URL_EMAIL = "/rest/V1/feedback/form/email"

        let url = "/" + storeCode + URL_EMAIL;
...

because __('text to translate') does not work in REST API code on server side w/o store view prefix.

1 Answer 1

2

follow below steps

1) in your block file

namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $_storeManager;    

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Store\Model\StoreManagerInterface $storeManager,        
        array $data = []
    )
    {        
        $this->_storeManager = $storeManager;        
        parent::__construct($context, $data);
    }

/**
     * Get Store code
     *
     * @return string
     */
    public function getStoreCode()
    {
        return $this->_storeManager->getStore()->getCode();
    }

2) in your phtml file

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "yourWidget": {
                    "storeCode": "<?php echo $block->getStoreCode(); ?>"
                }
            }
        }
    }
}
</script>

3) in your js file or define same into phtml file as you wish

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            this._super();
            console.log(this.storeCode);
        }
    });
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.