In this post I am going to explain how to add form key in phtml file.

Add below code snippet in Block class.

public function __construct(
	\Magento\Catalog\Block\Product\Context $context,
	\Magento\Framework\Data\Form\FormKey $formKey,
	array $data = []
) {
	parent::__construct($context, $data);
	$this->formKey = $formKey;
}

public function getFormKey()
{
	 return $this->formKey->getFormKey();
}

Add below code snippet in template file.

<?php echo $block->getBlockHtml('formkey')?>

The result is as below and you will find hidden form_key field inside the form.

<input name="form_key" type="hidden" value="8KnYuhbhWYxH4Lch">

That’s it. Enjoy Magento 2!!