Magento 2 Template – How to Override Template Files for Magento2 Extension

extensionsmagento2template

In magento2 to override template files here, but for magento2 extension we have to follow here.

So how to override template files in magento2 extension with out considering theme inheritance.

I want to override vendor\magento\module-ui\view\base\web\js\form\components\collection.js and vendor\magento\module-ui\view\base\web\templates\form\components\collection.html for customer address tab modifications.

With using theme inheritance i can do this by implementing above files in my custom theme files in Magento_Ui folder, but how could I achieve the same for magento2 extension i.e. with in app/code/vendor/module folder.

Best Answer

As far as I know, we can override js and html template via requirejs config. In our module, we create requirejs-config.js under view/frontend or view/adminhtml. For example, in your case:

app/code/{Vendor}/{Module_Name}/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            'Magento_Ui/js/form/components/collection':
                'Vendor_ModuleName/js/form/components/collection',
            'Magento_Ui/templates/form/components/collection.html':
                'Vendor_ModuleName/template/form/components/collection.html'
        }
    }
};

We can find the path of js and html files under pub/static.

In our module, create our custom js and html template:

app/code/{Vendor}/{Module_Name}/view/frontend/web/js/form/components/collection.js app/code/{Vendor}/{Module_Name}/view/frontend/web/template/form/components/collection.html

The most important thing is that after running static content deploy command, the js and html template files under web/js and web/template will be 'copied' to pub/static. For example, Magento Ui module:

enter image description here

Magento will get the js and html templates from pub/static. The all require config from requirejs-config.js will be also generated in pub/static/_requirejs. It handles the loading of js and html template files. So, requirejs helps us to override html template files.

Related Topic