node.js ejs_如何在Node.js应用程序中使用EJS模板

node.js ejs

by Jennifer Bland

詹妮弗·布兰德(Jennifer Bland)

如何在Node.js应用程序中使用EJS模板 (How to use EJS Templating in a Node.js Application)

EJS, embedded javascript, is a templating language. EJS combines data and a template to produce HTML. One of the most important features in EJS is its use of partials. Partials allow you to define something once, and then apply it to any page in your application.

EJS,嵌入式javascript,是一种模板语言。 EJS将数据和模板结合在一起以生成HTML。 EJS中最重要的功能之一是它对partials的使用。 局部函数允许您一次定义一些内容,然后将其应用于应用程序中的任何页面。

I will show you how to create a simple Node.js application that uses EJS as the templating engine. Then we will create 2 pages for a website. We will use partials to build out our head, navigation, footer and content.

我将向您展示如何创建一个使用EJS作为模板引擎的简单Node.js应用程序。 然后,我们将为网站创建2个页面。 我们将使用局部函数来构建我们的头部,导航,页脚和内容。

You can get the code for this example on github

您可以在github上获得此示例的代码

档案结构 (File Structure)

We will be creating a sample application that will have two pages: index and about.

我们将创建一个示例应用程序,该应用程序将具有两个页面:index和about。

Here is the file structure for the application we will be creating.

这是我们将要创建的应用程序的文件结构。

public — — style.css- routes — — index.js- views — — pages — — — — about.ejs — — — — index.ejs- partials — — — — 3columns.ejs — — — — footer.ejs — — — — head.ejs — — — — nav.ejs — — — — scripts.ejs- package.json- server.js
入门 (Getting Started)

We will setup our package.json first. This file will contain all the modules we will be using in our application. We will be using:

我们将首先设置我们的package.json。 该文件将包含我们将在应用程序中使用的所有模块。 我们将使用:

  • express

    表达
  • ejs

    ejs
{   “name”:    “node_ejs_boilerplate”,   “version”: “1.0.0”,   “description”: “Boilerplate showing the use of ejs as view template engine in a Node.js application”,   “author”: “Jennifer Bland”,   “main”: “server.js”,   “dependencies”: {       “ejs”: “^2.4.1”,       “express”: “^4.13.4”   }}

You can add the dependencies directly into your package.json or your can install the dependencies so that they are automatically added to the package.json. To manually install dependencies, enter this command:

您可以将依赖项直接添加到package.json中,也可以安装依赖项,以便将它们自动添加到package.json中。 要手动安装依赖项,请输入以下命令:

npm install express ejs  — save

If you added dependencies by adding them to your package.json, you will need to install them by using this commend:

如果通过将依赖项添加到package.json中来添加依赖项,则需要使用以下命令来安装它们:

npm install
Server.js (Server.js)

Now that we have all our dependencies installed, we need to build out application in server.js. Here is what our server.js file looks like.

现在我们已经安装了所有依赖项,我们需要在server.js中构建应用程序。 这是我们的server.js文件的样子。

‘use strict’;
// ================================================================// get all the tools we need// ================================================================var express = require(‘express’);var routes = require(‘./routes/index.js’);var port = process.env.PORT || 3000;
var app = express();
// ================================================================// setup our express application// ================================================================app.use(‘/public’, express.static(process.cwd() + ‘/public’));app.set(‘view engine’, ‘ejs’);
// ================================================================// setup routes// ================================================================routes(app);
// ================================================================// start our server// ================================================================app.listen(port, function() { console.log(‘Server listening on port ‘ + port + ‘…’);});

Our server will be listening on the port defined in process.env.PORT or 3000 if it is not defined.

我们的服务器将监听process.env.PORT或3000(如果未定义)中定义的端口。

We define a /public directory because this is how we will reach our stylesheet style.css located in the /public folder.

我们定义一个/ public目录,因为这是我们到达/ public文件夹中的样式表style.css的方式。

We define our templating engine to be ejs.

我们将模板引擎定义为ejs。

路线 (Routes)

To make our application follow the structure of a node.js application I have put the routes for our index and about pages into their own file. This file is index.js in the routes folder.

为了使我们的应用程序遵循node.js应用程序的结构,我将索引和关于页面的路由放入了自己的文件中。 该文件是路由文件夹中的index.js。

Since I have put the routes in their own folder I need to gain access to them by requiring them in the server.js file.

由于我已将路由放置在它们自己的文件夹中,因此我需要通过在server.js文件中要求它们来访问它们。

We have 2 routes in our application

我们的应用程序中有2条路线

  • / — this is a GET to display the homepage

    / —这是显示主页的GET
  • /about — this is a GET to display the about page

    / about-这是显示关于页面的GET

In the routes we use res.render to display the appropriate pages. The render command by default will look for files in a folder called views. We rely on this default and only add the path from within the views folder.

在路由中,我们使用res.render显示适当的页面。 默认情况下,render命令将在名为views的文件夹中查找文件。 我们依靠此默认值,并且仅从views文件夹内添加路径。

Here is our index.js file in the routes folder.

这是路由文件夹中的index.js文件。

‘use strict’;
module.exports = function(app) { app.get(‘/’, function(req, res) {   res.render(‘pages/index’); });
app.get(‘/about’, function(req, res) {   res.render(‘pages/about’); });};
配置我们的局部 (Configuring our partials)

For our sample application, I am going to implement four partials.

对于我们的示例应用程序,我将实现四个部分。

  • head — contains items found in the head section of a webpage

    标头-包含在网页标头部分中找到的项目
  • nav — the navigation that will be displayed on every page

    导航—将在每个页面上显示的导航
  • footer — static footer with link to my website

    页脚—带有我的网站链接的静态页脚
  • scripts- loading scripts like jQuery and Bootstrap

    脚本-加载jQuery和Bootstrap之类的脚本
  • 3columns — content that will be displayed on the homepage

    3栏-将显示在主页上的内容

Partials provide easy maintenance of your code. For example, if you create navigation on all of your pages, when you need to add a new entry to the navigation, you must then update every single page with this change.

局部提供了易于维护的代码。 例如,如果您在所有页面上创建导航,那么当您需要向导航添加新条目时,则必须使用此更改来更新每个页面。

The navigation partial will be inserted into every page that requires it. To add a new entry to the navigation, you need to just update the partial and it will automatically be applied to every page that contains the nav partial.

导航部分将插入到需要它的每个页面中。 要将新条目添加到导航中,您只需更新部分内容,它将自动应用于包含导航部分的每个页面。

Here are the contents of all of our partials.

这是我们所有部分的内容。

head.ejs

head.ejs

<! — views/partials/head.ejs →<head>  <meta charset=”UTF-8">  <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>  <meta name=”viewport” content=”width=device-width, initial-scale=1">  <! — The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags →  <title>Demonstration of EJS templating in NodeJS Application</title>
<! — STYLESHEETS →  <! — CSS (load bootstrap from a CDN) →  <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">  <link rel=”stylesheet” href=”/public/style.css”></head>

nav.ejs

nav.ejs

<! — views/partials/nav.ejs →<nav class=”navbar navbar-inverse navbar-fixed-top” role=”navigation”> <div class=”container”>
<div class=”navbar-header”> <a class=”navbar-brand” href=”/”> <span class=”glyphicon glyphicon glyphicon-cog”></span> CodePrep.io </a> </div>
<ul class=”nav navbar-nav pull-right”> <li><a href=”/”>Home</a></li> <li><a href=”/about”>About</a></li> </ul>
</div></nav>

footer.ejs

footer.ejs

<! — views/partials/footer.ejs →<footer class=”footer”> <div class=”container”> <p class=”text-center text-muted”>© Copyright 2015 <a href=”http://www.codeprep.io">CodePrep.io</a></p> </div></footer>

scripts.ejs

scripts.ejs

<! — views/partials/scripts.ejs →
<! — jQuery (necessary for Bootstrap’s JavaScript plugins) →<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><! — Bootstrap javascript file →<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

3columns.ejs

3列

<! — views/partials/3columns.ejs →<section name=”content”> <div class=”container”> <h2 class=”text-center”>Sample Data</h2> <div class=”col-xs-12 col-md-4"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eget iaculis lorem. Fusce elementum magna fringilla ipsum bibendum, vitae consectetur ligula interdum. Sed mauris diam, hendrerit eget suscipit vel, luctus at odio. Etiam pellentesque a metus et pharetra. Praesent dictum, libero id tempor malesuada, erat ex cursus nibh, ac hendrerit massa neque commodo metus. Integer porttitor ante eu varius interdum. Suspendisse quis iaculis erat. Fusce eu nisl id eros tempor posuere. Donec placerat orci orci, ut ultrices neque rutrum in. Nunc dignissim ante et risus rhoncus, vel feugiat mi vestibulum. Aliquam in dictum neque, non vestibulum lorem. Sed imperdiet dolor vitae felis iaculis, id sollicitudin lectus rhoncus. Maecenas ac dolor eget tortor rutrum commodo. Aliquam luctus iaculis mi id semper. Suspendisse sem nisi, convallis at dapibus in, convallis eu neque. Curabitur maximus magna et nulla ullamcorper facilisis.</p> </div> <div class=”col-xs-12 col-md-4"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eget iaculis lorem. Fusce elementum magna fringilla ipsum bibendum, vitae consectetur ligula interdum. Sed mauris diam, hendrerit eget suscipit vel, luctus at odio. Etiam pellentesque a metus et pharetra. Praesent dictum, libero id tempor malesuada, erat ex cursus nibh, ac hendrerit massa neque commodo metus. Integer porttitor ante eu varius interdum. Suspendisse quis iaculis erat. Fusce eu nisl id eros tempor posuere. Donec placerat orci orci, ut ultrices neque rutrum in. Nunc dignissim ante et risus rhoncus, vel feugiat mi vestibulum. Aliquam in dictum neque, non vestibulum lorem. Sed imperdiet dolor vitae felis iaculis, id sollicitudin lectus rhoncus. Maecenas ac dolor eget tortor rutrum commodo. Aliquam luctus iaculis mi id semper. Suspendisse sem nisi, convallis at dapibus in, convallis eu neque. Curabitur maximus magna et nulla ullamcorper facilisis.</p> </div> <div class=”col-xs-12 col-md-4"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eget iaculis lorem. Fusce elementum magna fringilla ipsum bibendum, vitae consectetur ligula interdum. Sed mauris diam, hendrerit eget suscipit vel, luctus at odio. Etiam pellentesque a metus et pharetra. Praesent dictum, libero id tempor malesuada, erat ex cursus nibh, ac hendrerit massa neque commodo metus. Integer porttitor ante eu varius interdum. Suspendisse quis iaculis erat. Fusce eu nisl id eros tempor posuere. Donec placerat orci orci, ut ultrices neque rutrum in. Nunc dignissim ante et risus rhoncus, vel feugiat mi vestibulum. Aliquam in dictum neque, non vestibulum lorem. Sed imperdiet dolor vitae felis iaculis, id sollicitudin lectus rhoncus. Maecenas ac dolor eget tortor rutrum commodo. Aliquam luctus iaculis mi id semper. Suspendisse sem nisi, convallis at dapibus in, convallis eu neque. Curabitur maximus magna et nulla ullamcorper facilisis.</p> </div> </div></section>
建立我们的页面 (Building our Pages)

Our sample application has a homepage and an about page. We will need to create both of these pages. On these pages we will insert the appropriate partials we just created on the page.

我们的示例应用程序有一个主页和一个关于页面。 我们将需要创建这两个页面。 在这些页面上,我们将插入刚刚在页面上创建的适当的部分。

We put all of our partials in a folder called partials within the views folder. We are going to create another folder in the views folder called pages. This folder will contain our homepage and about pages.

我们将所有的partials放置在views文件夹中的partials文件夹中。 我们将在views文件夹中创建另一个名为pages的文件夹。 该文件夹将包含我们的主页和关于页面。

To insert a partial on a page we use this format:

要在页面上插入部分内容,请使用以下格式:

<% include ../partials/head %>

Here are the contents of our two pages:

这是我们两个页面的内容:

index.ejs

index.ejs

<!DOCTYPE html><html lang=”en”>
<% include ../partials/head %>
<body>
<% include ../partials/nav %>
<section name=”jumbotron” > <div class=”jumbotron text-center”> <h1>CodePrep.io Presents</h1> <p>Using EJS templating with Node.js</p> </div> </section>
<% include ../partials/3columns %>
<% include ../partials/footer %>
<% include ../partials/scripts %>
</body>
</html>

about.ejs

about.ejs

<!DOCTYPE html><html lang=”en”>
<% include ../partials/head %>
<body>
<% include ../partials/nav %>
<! — content for about page → <div class=”container” id=”about”> <div class=”row”> <h2 class=”text-center”>About Page</h2> <div class=”col-xs-12"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien eros, dictum eu malesuada sagittis, pellentesque sed enim. Donec at odio volutpat, dignissim mauris tincidunt, pharetra lorem. Fusce porta neque non lorem vulputate, et commodo dolor semper. Proin sodales lacinia nibh vel semper. Nulla sed faucibus nisi. Aliquam venenatis pellentesque tortor et fringilla. Nulla porttitor massa vitae libero volutpat, id mollis neque elementum. Integer porta, enim eu pharetra interdum, diam metus mollis purus, id ornare risus enim a magna. Sed rhoncus, nulla ac hendrerit lacinia, neque lectus iaculis ligula, et euismod erat massa sit amet orci. Ut fermentum hendrerit arcu. Vestibulum quis leo ut ante eleifend fringilla.
Morbi maximus eu lorem sit amet tempor. Nunc dignissim lacus vel aliquet ornare. Aliquam eget turpis et nisi tincidunt rhoncus. Vestibulum interdum interdum aliquet. Phasellus quis erat est. Pellentesque molestie pretium quam in fermentum. Maecenas eu luctus turpis, euismod feugiat risus. Integer scelerisque cursus tempor. Phasellus in bibendum tortor.
Aenean vitae lorem augue. Cras ultricies posuere vestibulum. Integer non felis porttitor mi ultricies pretium. Sed vitae nisi accumsan, maximus lorem sed, malesuada quam. Nunc lacus est, elementum vel ultrices sit amet, suscipit eu nibh. Maecenas vel facilisis leo, id congue sem. In hac habitasse platea dictumst. Aenean est lorem, hendrerit sit amet rutrum ac, sodales eget neque. Pellentesque hendrerit, risus in bibendum varius, purus tellus accumsan leo, et suscipit lorem nulla non arcu.</p> </div>
</div> </div><! — end of content →
<% include ../partials/footer %>
<% include ../partials/scripts %>
</body></html>
开始我们的申请 (Starting our Application)

To start the application enter the following command:

要启动该应用程序,请输入以下命令:

node server.js

When our application starts it will display our homepage:

当我们的应用程序启动时,它将显示我们的主页:

If you click on the about link in the navigation, you will see the about page:

如果单击导航中的“关于”链接,将看到“关于”页面:

获取代码 (Get the code)

You can get the code for this example on github

您可以在github上获得此示例的代码

Thanks for reading my article. If you like it, please click on clap icon below so that others will find the article. Here are some more of my articles that you might be interested in:Using Node.js & Express.js to save data to MongoDB DatabaseFirst Impressions Count — Why Doesn’t Your Github Repo Have a ReadMe File?Why Company Culture is Important to Your Career as a Software Engineer

感谢您阅读我的文章。 如果喜欢,请单击下面的拍手图标,以便其他人可以找到该文章。 以下是您可能感兴趣的其他一些文章: 使用Node.js和Express.js将数据保存到MongoDB数据库的 第一印象数-为什么您的Github Repo没有自述文件? 为什么公司文化对您作为软件工程师的职业很重要

翻译自: https://www.freecodecamp.org/news/how-to-use-ejs-templating-in-a-node-js-application-ea9347a96c65/

node.js ejs

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值