How to include external .js file to ejs Node template page

 ̄綄美尐妖づ 提交于 2019-11-29 14:31:33

You can't.

Note: You can only pass data from .ejs file to .js file but not the other way. It won't work because .ejs is rendered on the server side while .js runs on the client side. I am assuming you are using EJS on server side

1) You can pass an ejs variable value to a Javascript variable

    <% var test = 101; %> // variable created by ejs
    <script>
       var getTest = <%= test  %>;  //var test is now assigned to getTest which will only work on browsers
       console.log(getTest);  // successfully prints 101 on browser
    </script>

2) You can't pass a js variable value to a ejs variable

Yes, you can't: if it is on server.

Why:

The EJS template will be rendered on the server before the js is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.

A workaround with Express:

myScripts.js

module.export = {
 foo() {
 },
 bar() {
 }
}

Then in your app.js

var myScripts = require('/path/to/myScripts');

res.render('template', {
  utils: myScripts
}

then in your template.ejs

// utils will act in global scope for this file
<%
  utils.foo();
  utils.bar();
%>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!