简体   繁体   English

在Express中使用函数(nodeJS框架)

[英]Using functions in express (nodeJS framework)

I am learning nodeJS, for that I have found a good set of turtorials. 我正在学习nodeJS,为此我找到了一套不错的教程。 Right now it's teaching me about a good framework called express. 现在,它正在教会我一个叫做express的好的框架。 To use express you must also learn ejs. 要使用express,您还必须学习ejs。 luckily for me the turtorials also cover that. 幸运的是,我的课程也涵盖了这一点。 I now know that you can basically embed javascipt object values like this: 我现在知道,您基本上可以像这样嵌入javascipt对象值:

<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. 不过,我还没有学到如何在ejs / express中使用其他javascript功能。 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? 所以我的问题基本上是:是否可以像使用普通前端javascript一样用express做相同的事情? And if so, does anyone have a good link that could explain to me how it works? 如果是这样,是否有人能很好地向我解释它的工作原理?

EJS is a templating language. EJS是一种模板语言。 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. 您应该在EJS中执行的唯一逻辑是影响视图的逻辑。 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. 例如,您提供的for循环,或者说if语句说明数据不存在或不符合要求,则不会渲染显示数据的部分。 The code below is stating only put the label-danger on the page if we have more than 0 unread errors messages. 下面的代码仅在我们有0多个未读错误消息的情况下才将标签危险置于页面上。

<%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. 您应该处理数据并在节点中执行其他逻辑,然后将它们传递给EJS进行渲染和渲染。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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