Where should I define JS function to call in EJS template
Create common functions in js file helper.js.
function common1() {
//function body
}
function common2(key) {
//function body
}
module.exports = {
common1: common1,
common2: common2
}
And then require this file in your node function
var helper = require('./helper');
and then pass this helper with ejs render
res.render('index', { helper:helper });
And use your function is ejs file
<%= helper.common1() %>
That's It
Just posting this answer here for someone who would might end up on this question while resolving same issue.
All you have to do is create new file (say functions.ejs
) and include it in the .ejs file where you want to call that function. So, I have function like this in file named functions.ejs
:
<%
getPriceChgArrow = function(value) {
arrow_img_name = "";
if (value < 0) {
arrow_img_name = "arrow_down12x13.gif";
}
else {
arrow_img_name = "arrow_up12x13.gif";
}
return arrow_img_name;
}
%>
Then include functions.ejs
into the file you want to call function from. Say, I want to call this function in quote.ejs
file. So, I would include it as follows:
<% include *file_path*/functions %>
Just use this function at appropriate location in your ejs file from where you want to call it. For example:
<img src = "http:/some_url/<% getPriceChgArrow(data_point[0].value) %>" />
and you are all set. Hope this helps someone.
Well, for some reason the accepted answer didn't worked out for me. Also it doesn't makes sense to create a separate *.ejs
file for each of my functions and then importing the file in view - specially when I have very simple logic to be implemented.
In fact it is very simple and easy to define function and use it in the view
I did this:
<%
// ------ Define a function
get_tree = function(tree){
for(var i in tree){
%>
<%= tree[i].title %>
<%
}
}
// ----- Call the above declared function
get_tree(tree);
%>
And it works!
Thanks
You can just require a separate file and set app.locals to this
app.locals = require('./path/helpers')
In helpers.js:
getFlag = function(country) {
var flag_img_name = "";
if (country.toLowerCase() == "us") {
flag_img_name = "flag_us16x13.gif";
}
else if (country.toLowerCase() == "ca"){
flag_img_name = "flag_ca16x13.gif";
}
return flag_img_name;
}
anotherFunction=function(x){
return 'hello '+x
}
module.exports={getFlag, anotherFunction}