How to call phtml file from html in Magento 2?
-
05-02-2021 - |
Question
I have included a custom button in checkout page on click of that I should get my phtml file as popup.
I have created a button in my custom module.
\view\frontend\web\template\checkout\custom-checkout-page.html
Please help me in which path I should add my phtml file and how can I add it ?
Should I use any di?
Solution
We create our phtml:
app/design/frontend/{Vendor}/{theme}/Magento_Checkout/templates/html/my-custom.phtml
<?= /* @escapeNotVerified */ __('My html is loaded') ?> <h3>successfully !</h3>
We instantiate our custom phtml:
app/design/frontend/{Vendor}/{theme}/Magento_Checkout/templates/onepage.phtml
/* The Magento onepage code first, then we add our myphtml var bellow the initial file code, this file if you haven't it yet in your current theme, you can copy it from : vendor\magento\module-checkout\view\frontend\templates\onepage.phtml*/ ... <?php $myphtml = $block->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Theme::html/my-custom.phtml")->toHtml(); ?> <script type="text/javascript"> var my_phtml = <?php echo json_encode($myphtml); ?>; </script>
We go to our html file then we create our popup and bind our phtml content
for exmple: we add our popup in
shipping.html
file:app/design/frontend/{Vendor}/{theme}/Magento_Checkout/web/template/shipping.html
... <div id="my-dialog-id" title="Information" data-bind="html:my_phtml" style="display:none;"/> <button data-bind="click: function(){ jQuery(function() { jQuery('#my-dialog-id').dialog(); }); }">Show me my popup</button>
Info: make sure that you have well code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css
in your theme.