简体   繁体   中英

Using functions in express (nodeJS framework)

I am learning nodeJS, for that I have found a good set of turtorials. Right now it's teaching me about a good framework called express. To use express you must also learn ejs. luckily for me the turtorials also cover that. I now know that you can basically embed javascipt object values like this:

<div><%= valueKey %></div> //Here I have embedded valueKey

And you can also do things with loops like this:

<ul><% (for var i=0; i<5; i++){ %>
    console.log(i)
 <% } %></ul>

What I haven't learned though, is how you can use other javascript functionalities with ejs/express. Like events for example. And since this is essential for making a site, I am wondering wheter or not this is even possible. So my question basically is: Is it possible to do the same things with express as you would using normal front end javascript? And if so, does anyone have a good link that could explain to me how it works?

EJS is a templating language. The goal of template language is to describe how the view should look like. Which means, you shouldn't do business logic in them. The only logic you should do inside EJS is the ones that affect the view. For example the for loop you provided, or a if statement saying if a data doesn't exist or doesn't fit a requirement don't render the part that shows the data. The code below is stating only put the label-danger on the page if we have more than 0 unread errors messages.

<%if (unreadErrorNumber>0){%>
    <span class="label label-danger"><%=unreadErrorNumber%></span>
<% } %>

You should manipulate the data and do other logic in node and then pass them into EJS for rendering and rendering only.

app.get("/index", (req, res, next) => {
    //Do what it takes to get the correct unreadErrorNumber.
    let errorCount = modification(databaseStuff());
    res.render("index", unreadErrorNumber:errorCount);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM