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

。_饼干妹妹 提交于 2019-12-17 16:58:24

问题


I cannot find a way to include external .js file to Node ejs template. I want to put logic and data into object in external .js file, include that file to index.ejs template and pull data from it.

I tried by inserting standard way <script src="sample.js"></script>, and it doesn't work

Then I tried ejs specific keyword <% include partials/sample.js %> and this works only for adding partials (ejs code snippets).

I inserted .js file into static directory which is defined in executable server.js, no results again.

But interestingly, including css file into ejs template classic way works fine, for example

<link href="/assets/styles.css" rel="stylesheet" type="text/css" />

Workaround would be to include external ejs file where I would put logic and data inside <% %> tags, but this is obviously a patch and not a viable solution, because ejs is not a js file. Besides, it doesn't work.

I cannot find any solution on Internet. Any hint?

Thanks


回答1:


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.




回答2:


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
}); // you forgot a ')' here              

then in your template.ejs

// utils will act in global scope for this file
<%
  utils.foo();
  utils.bar();
%>


来源:https://stackoverflow.com/questions/47001537/how-to-include-external-js-file-to-ejs-node-template-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!