vendor/magento/module-contact/Controller/Index/Post.php set in session messages like

    __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')

How do I access these messages in phtml?


You need to use dependency injection in order to load message manager in your block.

protected $messageManager;

public function __construct(
    Template\Context $context,
    \Magento\Framework\Message\ManagerInterface $messageManager,
    array $data = [])
    $this->messageManager = $messageManager;
    parent::__construct($context, $data);

Then you can implement new method getMessages in the same block which will retrieve recent messages from manager.

public function getMessages()
    $messages = array();
    $collection = $this->messageManager->getMessages(true);
    if ($collection && $collection->getItems()) {
        foreach ($collection->getItems() as $message) {
            $messages[] = $message->getText();
    return $messages;

And finally you can call method getMessages in block template.

<?php if ($messages = $block->getMessages()): ?>
    <?php foreach ($messages as $message): ?>
        <h1><?php echo $block->escapeHtml($message) ?></h1>
    <?php endforeach; ?>
<?php endif; ?>

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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