express中使用ejs
Hi! Welcome to NODE AND EJS TEMPLATE ENGINE SERIES. Today, we will write our first code in using EJS as template engine or view engine.
嗨! 欢迎使用NODE和EJS模板引擎系列 。 今天,我们将使用EJS作为模板引擎或视图引擎编写第一个代码 。
Take Note! You should have Node.js installed in your before you can start using EJS in this article.
做记录! 在开始使用EJS之前,您应该已经安装了Node.js。
To download Node JS, visit nodejs.org.
要下载Node JS,请访问nodejs.org 。
Then install.
然后安装。
* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED.
*必须具备基本NODE.JS /快速知识。
To begin, ensure you have EJS and express installed via npm.
首先,请确保您已通过npm安装了EJS和express。
To install EJS, simply open a terminal/command prompt and type the following command.
要安装EJS,只需打开终端/命令提示符并键入以下命令。
npm install ejs
or
npm install ejs –save
You can use either command prompt or PowerShell as terminal.
您可以使用命令提示符或PowerShell作为终端。
We will create 2 files, one for our express server file and the second our EJS file.
我们将创建2个文件,一个用于快速服务器文件,第二个用于EJS文件。
Open your text editor and type the following code, Save as app.js.
打开文本编辑器,然后输入以下代码,另存为app.js。
var express = require ('express');
var app = express();
app.get ("/", function (req,res) {
res.render ( "hello.ejs" );
} );
app.listen(3000 , function () {
console.log ("server is listening!!!");
} );
Unlike any other express app, we used res.render then the ejs file and not res.send.
与任何其他Express应用程序不同,我们使用res.render然后使用ejs文件,而不使用res.send 。
Also, I didn't require the ejs app. There's no problem!. You can do so if you wish.
另外,我不需要ejs应用。 这里没有问题!。 如果您愿意,可以这样做。
Now, let's create our EJS file.
现在,让我们创建我们的EJS文件。
Open a text editor and type the following code, Save as hello.ejs
打开文本编辑器,然后输入以下代码, 另存为hello.ejs
<h1>Hello EJS World </h1>
Create a folder in your app.js directory called views.
在app.js目录中创建一个名为views的文件夹。
Cut and paste the ejs file in the views folder.
将ejs文件剪切并粘贴到views文件夹中。
Take Note: The folder name views are not a random word I selected but it's the reserved folder name where express checks for template engine by default.
请注意:文件夹名称视图不是我选择的随机词,而是默认情况下Express检查模板引擎的保留文件夹名称。
Finally, initiate the app.js file and view the port in a browser, localhost:3000
最后,启动app.js文件并在浏览器localhost:3000中查看端口
Or for those using nodemon, use
或对于那些使用nodemon的人,使用
There's yet another way to code hello world using EJS which will be disclosed in the next article.
还有另一种使用EJS编写Hello World的方法 ,将在下一篇文章中介绍。
Thanks for coding with me! Feel free to drop a comment or question.
感谢您与我编码! 随意发表评论或问题。
翻译自: https://www.includehelp.com/node-js/hello-world-in-node-express-and-ejs-1-introduction-to-ejs.aspx
express中使用ejs