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();

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

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 *