Siraphob K.
Siraphob K.

Reputation: 57

Can't call function in ejs template

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. :)

Upvotes: 2

Views: 5021

Answers (2)

Nuriddin Kudratov
Nuriddin Kudratov

Reputation: 518

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.

Upvotes: 0

Quentin
Quentin

Reputation: 943759

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.

Upvotes: 2

Related Questions