Magento 2 JS – How to Get Current Currency Symbol

currencyknockoutjsmagento2

I want to use current currency symbol in custom module Js.

define([
'jquery',
'ko',
'uiComponent'
], function ($, ko, component) {
    'use strict';
    return component.extend({
        initialize: function () {
            this._super();
            this._render();
        },
        _render:function(){
            var self = this;
            console.log("need current currency symbol here.");
        },
        defaults: {
            template: 'Namespace_Modulename/product/view/price',
        },
    });
});

Any suggestion would be appreciated.

Thanks

Best Answer

For this first you have to create a block file as below:

<?php
class Customclass{
    protected $_currency;
    public function __construct(        
        \Magento\Directory\Model\Currency $currency,
    ){       
        $this->_currency = $currency;
    }

    public function getStoreCurrencySymbol(){
        return $this->_currency->getCurrencySymbol();
    }
}

In it's template you need to call above function and pass the value to your js file as below:

<script>
    window.getCurrency = {
            "getCurrencySymbol":<?php /* @noEscape */ echo $block->getStoreCurrencySymbol(); ?>
        };
</script>
<div class="my-class">
    <div id="my-id" data-bind="scope: 'curency-symbol'">
        <!-- ko template: getTemplate() --><!-- /ko -->
        <script type="text/x-magento-init">
        {
            "#decoration-tier-price": {
                "Magento_Ui/js/core/app": <?php /* @escapeNotVerified */ echo $block->getJsLayout(); ?>
            }
        }
        </script>
    </div>
</div>

create your js file as below where you will get your current currency symbol.

define([
'jquery',
'ko',
'uiComponent'
], function ($, ko, component) {
  'use strict';

  return component.extend({
    initialize: function () {
      this._super();
      this._render();
    },
    _render: function () {
      var self = this;
      var getCurency = window.getCurrency;
      console.log(getCurency.getCurrencySymbol)
    },
    defaults: {
      template: 'namespace_modulename/template/path',
    },
  });
});
Related Topic