Magento2 – How to get Current locale Programmatically

Magento2 – How to get Current locale Programmatically
Inject Resolver Dependency and get locale in your phtml
 
<?php
namespace Vendor\Namespace\Block;
/**
* Class MyClass
* @package Vendor\Namespace\Block
*/
class MyClass extends \Magento\Framework\View\Element\Template {

    /**
    * @var \Magento\Framework\Locale\Resolver
    */
    private $_localeResolver;

    /**
    * MyClass constructor.
    * @param \Magento\Framework\View\Element\Template\Context $context
    * @param \Magento\Framework\Locale\Resolver $resolver
    * @param array $data
    */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Locale\Resolver $resolver,
        array $data = []
    ) {
        $this->_localeResolver = $resolver;
        parent::__construct($context, $data);
    }

    /**
    * @return null|string
    */
    public function getLocale() {
        return $this->_localeResolver->getLocale();
    }
}
And in your phtml:
 echo $block->getLocale();

3 Comments

  • How about calling this without the object manager – Object manager is bloated in PHTML files

    • Yeah Sure, You can inject in the class constructor

    • Thanks for your feedback. I’ve updated the post.

Leave a Reply

Your email address will not be published. Required fields are marked *