Where should I define a JS function to call in an EJS template
I am working on a template where I am trying to create a template using express and ejs. Regarding the standard node application structure, I have an app.js file that contains the following functions:
app.locals.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;
}
I have a file some_template.ejs that calls this function like this:
<img src="http://some_url_path/<%=getFlag(data_point[0].country_name) %>" width="16" height="14" alt="country" >
and everything works fine. However, I have about 15-20 functions like this and I don't want to define them in app.js. Is there some other place where I can define these functions and call them in the template the same way I do now? If so, how can you define them so that they are available as they are now.
I am new to node, express and ejs and not sure about different methods. If someone could shed some light on this it would be great. Thank you in advance.
source to share
Just post this answer here for anyone who might be able to resolve this issue while solving the same problem.
All you have to do is create a new file (say functions.ejs
) and include it in the .ejs file where you want to call this function. So, I have a function like this in a 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
in the file from which you want to call the function. Let's say I want to call this function on a file quote.ejs
. So I would include it in the following:
<% include *file_path*/functions %>
Just use this function in the appropriate place 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 in tune. Hope this helps someone.
source to share
Well, somehow the accepted answer didn't work for me. It also doesn't make sense to create a separate file*.ejs
for each of my functions and then import the file into view - especially when I have very simple logic to be implemented.
It's actually very simple and easy to define a function and use it in a 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!
thank
source to share