The ejs view engine populates the data
express build project
Install express-generator
The windows system executes the following command
npm install -g express-generator
Verify whether the installation is successful, the following information appears to indicate that the installation is successful
C:\Users\Administrator>express --version
4.16.1
C:\Users\Administrator>express -h
Usage: express [options] [dir]
Options:
--version output the version number
-e, --ejs add ejs engine support
--pug add pug engine support
--hbs add handlebars engine support
-H, --hogan add hogan.js engine support
-v, --view <engine> add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
--no-view use static html instead of view engine
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
-h, --help output usage information
build project
- Execute the following command
F:\Github\Nodejs>express --ejs --view=ejs photo
warning: option `--ejs' has been renamed to `--view=ejs'
create : photo\
create : photo\public\
create : photo\public\javascripts\
create : photo\public\images\
create : photo\public\stylesheets\
create : photo\public\stylesheets\style.css
create : photo\routes\
create : photo\routes\index.js
create : photo\routes\users.js
create : photo\views\
create : photo\views\error.ejs
create : photo\views\index.ejs
create : photo\app.js
create : photo\package.json
create : photo\bin\
create : photo\bin\www
change directory:
> cd photo
install dependencies:
> npm install
run the app:
> SET DEBUG=photo:* & npm start
- install dependencies
cd photo
npm install
- start service
SET DEBUG=photo:* & npm start
- The browser accesses http://127.0.0.1:3000/, the page shown in the figure appears, and the project is successfully generated
program structure understanding
project structure
Meaning of generated files
- app.js, the main program file
- public stores static resource folders, stores the resources required by the client, such as js, css
- routes router folder, fill the logic of page data, find the corresponding view page
- views view page
View rendering populated with photo data
add router
Modify app.js
When the original app.js file was generated, there were already two routers
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
Add a router corresponding to a photo program
var photoRouter = require('./routes/photo');
Use this router when accessing /photo
app.use('/photo', photoRouter);
complete app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var photoRouter = require('./routes/photo');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// app.set('view cache', false);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/photo', photoRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {
};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
modify routes
Create a new photo.js under the routes folder, and write the method to be executed by the router. You can refer to idnex.js to write
var express = require('express');
var router = express.Router();
var photos = [];
photos.push({
'name': 'photo1',
'path': 'https://img1.doubanio.com/dae/niffler/niffler/images/abd3c3ec-922c-11e7-8a20-0242ac11000c.png'
});
photos.push({
'name': 'photo2',
'path': 'https://img9.doubanio.com/dae/niffler/niffler/images/6db31128-39dd-11e7-895e-0242ac110016.png'
});
/* GET photo page. */
router.get('/', function(req, res, next) {
res.render('photos', {
title: 'Photos', data: photos });
});
module.exports = router;
Add the corresponding view page
- Create a new photos folder
- Add index.ejs, copy the index.ejs under the original views file
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>照片存储应用</p>
<div id="photos">
<% data.forEach(item => {
%>
<div class="photo">
<h2><%=item.name%></h2>
<img src='<%=item.path%>'/>
</div>
<%})%>
</div>
</body>
</html>
Router res.render looks for view logic
-- app.js
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
-- view/photos/index.ejs
res.render('photos', {
title: 'Photos', data: photos });
The logic of ejs view engine rendering photo data is as follows
<div id="photos">
<% data.forEach(item => {
%>
<div class="photo">
<h2><%=item.name%></h2>
<img src='<%=item.path%>'/>
</div>
<%})%>
</div>
Note: The relevant js code and the part of fetching data need to be enclosed with <% %>
Project structure diagram after adding files
renderings
start service
F:\Github\Nodejs\photo>SET DEBUG=photo:* & npm start
> [email protected] start
> node ./bin/www
photo:server Listening on port 3000 +0ms
GET /photo 200 16.911 ms - 701
GET /stylesheets/style.css 304 2.801 ms - -
Browser access http://127.0.0.1:3000/photo