4

How to include js file in phtml file.

eg:

if(some text){
 add js file here.....
}

Any idea?

Thanks

1

4 Answers 4

13

The best way to add js in phtml is via requirejs

Theme solution :

Supposing that your js file is: myfile.js

app/design/frontend/{Vendor}/{theme}/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'js/myfile'
        }
    }
};

app/design/frontend/{Vendor}/{theme}/web/js/myfile.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, got it.");
       }
});

app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/{yourfile}.phtml

<?php if(condition here): ?>
    <script>
        require(['jquery', 'myscript'], function($, myscript) {
            myscript();
        });
    </script>
<?php endif;?>

Module solution :

app/code/Vendor/Module/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'Vendor_module/js/myfile',
        }
    }
};

app/code/Vendor/Module/view/frontend/web/js/myfile.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, got it.");
       }
});

app/code/Vendor/Module/view/frontend/templates/{yourfile}.phtml

<?php if(condition here): ?>
    <script>
        require(['jquery', 'myscript'], function($, myscript) {
            myscript();
        });
    </script>
<?php endif;?>

Info: don't forget to :

  • clean the cache

  • clean var/view_preprocessed content

  • clean pub/static content

  • deploy the static content = php bin/magento setup:static-content:deploy -f

4
  • How to add requirejs-config.js in custom module?
    – Shomita
    Jan 20, 2020 at 9:57
  • look my update.
    – PЯINCƎ
    Jan 20, 2020 at 10:11
  • Thanks..Let me check
    – Shomita
    Jan 20, 2020 at 10:21
  • I don't want to make function in js file. need to call in document ready
    – Shomita
    Jan 21, 2020 at 5:25
4
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Theme/js/customjs" : {
            }
        }
    }
</script>

This is my way to add JS in any .phtml. Add this at the end of phtml to call particular JS.

1
  • I like this solution as it uses the Magento framework standards - following their methods for adding external scripts in a CSP friendly method.
    – PromInc
    Feb 19, 2021 at 16:09
3

If you need to write the script for a particular page with the condition than write down the script into phtml based on your condition.

Like this way !!!

<?php
if (condition) { ?>
    <script>
    require(['jquery','domReady!'], function ($) {
        //write down the script
    }); 
    </script>
<?php } ?>

Secound Method

<?php if (condition) { ?>
    <script src="<?php echo $block->getViewFileUrl('Magento_Catalog::js/script.js')?>"></script>
<?php } ?>
2
  • I did the same. My js code is too big. so i need to create seperate js for this and call on the same place.
    – Shomita
    Jan 20, 2020 at 9:10
  • I have added the second method please check and implement. Jan 21, 2020 at 6:36
0

You'll call js using the below code in .phtml file if your condition is fulfilled.

Add the below code in your .phtml file.

<?php if(condition): ?>
<div id="div-ko-example" data-bind="scope:'div-ko-example'">
     <h2 data-bind="text: message"></h2>
</div>

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
           "components": {
                "div-ko-example": {
                    "component": "Vendor_Modulename/js/ko_template"
                    }
                }
            }
        }
}
</script>
<?php endif; ?>

Also, create js file name with ko_template.js at app/code/Vendor/Modulename/view/frontend/web/js/ko_template.js And write code as per your need. See the below code for your reference.

define(['ko'], function(ko) {
    return function(config) {
        this.message = ko.observable(config.exampleMessage);
    }
});

Please Note: it's not an exact code as per your requirement. I just give you a reference that you'll fulfill your requirement by call js using knockout like above example.

I hope this will help you.

2
  • Can you please describe more your answer?
    – Shomita
    Jan 20, 2020 at 9:08
  • @Shomita I have updated my answer just for your understanding. Please check.
    – MK Patel
    Jan 20, 2020 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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