Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...