2

I'm having a problem about calling a function in ejs file.

I have the separated js file 'main.js' which is

// this is main.js
var hello = function() {
   return "hello";
}

I want to call hello() in my ejs file but it returns an error.

hello is not defined

This is my ejs file

<script src="path/main.js"></script>
<%= hello() %>   ***this is where the error occurs.

If anyone knows how to fix this please tell me. I appreciate all your helps. :)

Siraphob K.
  • 57
  • 2
  • 6
  • https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – Quentin Jul 05 '18 at 06:12
  • Did you require the separate script? Javascript cant magically know where to access your code from. Otherwise, we would have a serious security issue – Derek Pollard Jul 05 '18 at 06:13
  • Of course you can't do that. Your `ejs` render and managing by nodejs on serve side. Your `main.js` is on client browers... – Truong Dang Jul 05 '18 at 06:13
  • @truongdang - you can render EJS either client side or server side – Derek Pollard Jul 05 '18 at 06:15

2 Answers2

2

You have two JavaScript programs.

One renders the template. The other runs in the webpage that is created from the output of the rendering.

You need to load the function into the former.

By generating a script element in the output from the template, you are loading it into the latter.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

I have faced with the same issue just a couple days ago. So you should create two ejs files. For example, your function is in hello.ejs

<%
var hello = function() {
   return "hello";
}
%>

In main.ejs file, you should include hello.ejs like that

<% include *file_path*/hello%> 

There might be other solutions but I recommend you to use like that.