What is the ejs
Compare handlebars, artTemplate, Jade, etc. Ejs is also a javascript template engine. We won’t compare its performance with other template engines here. Ejs syntax is too simple, if you can write HTML and simple javascript, Or if you’ve written React in JSX, ejS will be a breeze for you. Just two simple steps:
- will
%
Label wrappedjs
Grammar is written in thehtml
In the - will
html
Replace the file name suffix withejs
It’s a perfect fit for developing web sites with Node, because it’s a template based on the Node ecosystem and can run in node projects with simple configuration. Ejs combines templates with data to build HTML pages quickly and efficiently. Each EJS can be used as an HTML or component, and specific EJS syntax usage can be viewed in the EJS documentation
In actual combat
Step 1: Set up a server using KOA
The project is initialized first and executed in turn on the terminal
npm init
npm install koa
Copy the code
Create an app.js entry file with the following code:
const koa = require('koa') const app = new koa() app.use(async(ctx, Next) => {console.log(ctx.request.path) if (ctx.request.path === '/index') {// home ctx.response.status = 200 Ctx.response.body = 'index'} else if (ctx.request.path === '/hello') {// Hello page ctx.response.status = 200 ctx.response.body = 'hello world' } else { ctx.throw(404, 'Not found') // 404 } await next() }) app.listen(3000, Function () {console.log(' Koa app started! ')})Copy the code
As shown in the above code, the path path is accessed based on the parameter CTX, and then the different paths are processed separately
Terminal operation
npm app.js
Copy the code
Start the KOA service and see the following:
This is a simple KOA project, listening on 3000 to start the Node service, index page and Hello page to display different content. Now that the first step is complete, all you need to do is integrate the EJS template engine into your KOA project.
Step 2: Integrate ejS template engine
Create a new view directory and place all ejS template files in this directory. As a demonstration, we will create a new index. Ejs file, koA can not recognize the ejS suffix file, we need to use app. Associate koA with all EJS suffix files in the views directory.
First, install koA-views
npm install koa-views
Copy the code
Add the following code to app.js:
const path = require('path')
const views = require('koa-views');
app.use(views(path.join(__dirname, './views'), { extension: 'ejs' }))
Copy the code
And modify the following code
app.use(async(ctx, Next) => {console.log(ctx.request.path) if (ctx.request.path === '/index') {// home // ctx.response.status = 200 // Ctx.response.body = 'index' await ctx.render('index')} else if (ctx.request.path === '/hello') {// Hello page ctx.response.status = 200 ctx.response.body = 'hello world' } else { ctx.throw(404, 'Not found') // 404 } await next() })Copy the code
Ctx.render (‘index’) renders index.ejs to HTML with the following code:
<! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> </head> <body style="overflow-y: scroll;" </div> </body> </ HTML >Copy the code
Rerun thenpm app.js
, start the service, refresh the Index page, and see that the EJS template has been compiled into onehtml
Page, as shown below:
Apply it to actual projects
Scenario 1: Quickly Setting up a Static Web site
If you need to build a site quickly, this is a good solution. You can use KOA, but you can also use the Node or Express framework. Since EJS is part of the Node ecosystem, you can use any Node framework. In a real project, we might use koA-Router to manage multiple routes, with render corresponding EJS files in each route, as shown in the figure below:
The demo sample
Scenario 2: Build a complex business website
Above is simply introduce how to quickly build a static web site, the page in our actual project will become more complex, not only static pages, forms, lists, and so on exist a large number of pages to dock with the interface alignment, so there will be some ejs templates to do dynamic processing, of course also support ejs template syntax. For how to obtain dynamic data and render dynamic pages, there are two schemes:
1, kao+ EJS +MySQL
The back-end Node service directly connects to the database, queries the data and returns to the EJS page. According to EJS syntax, we get the variables from the route and render them in the EJS template. At this point, the whole Node project is not separated from the front and back end, Node does both back-end services and front-end rendering, if it is a complex project, the developer may be relatively large amount of development, of course, for full stack developers or entrepreneurial companies, these are not a problem.
Connect to the database, get data, back-end render, straight out of the page
Set the front-end routes of the Demo page in the Routers/Demo.js of the Node sample project. The demo page renders a set of data directly obtained from the database
router.get('/demo', Async CTX => {console.log(' connect to database ') let result = await usermodule.find (ctx.query) let imgs = [] result && Result.filter (item => {imgs.push(item.telephone)}) await ctx.render('demo', {title: 'demo', tableData: imgs})})Copy the code
The front-end code inside views/demo.ejs in the Node sample project is as follows:
< p style=" max-width: 100%; clear: both; > <% tableData.forEach(function(item,index){%> <li data-id="<%= index %>" style="float: left; margin:0 10px;" > <%= index %> <img style="width:100px" src="<%= item %>" /> <%= item %> </li> <% })%> </ul>Copy the code
The page effect is as follows:
The data in the database is as follows:
The demo sample
Form submission invocation interface
Set up toSingUp interface routes in the Routers/Demo. js area of the Node sample project
Router. post('/toSingUp', async CTX => {console.log(' toSingUp', ctx.request.body); const { telephone, password, companyName } = ctx.request.body let result = await UserModule.findUserByTelephone({ telephone }) let isNewRecord = result && result.isNewRecord if (isNewRecord === null) { await UserModule.add({ telephone, password, CompanyName}) await ctx.render('signUp', {title: 'application experience page ', message:' Congratulations! '})} else if (isNewRecord === false) {await ctx.render('signUp', {title: 'request ', message:' request ')}})Copy the code
Click “Apply for experience” in the Demo page to enter the form page. After filling in the form, click OK to request toSingUp interface and save the form data into the database. The page effect is as follows:
The submitted form data has been inserted into the database, as shown below:
2, KAO + EJS + Request/Ajax (front end separation)
You can also use the Request library (such as Ajax, AXIOS, HTTP, FETCH) to request third-party interfaces within the route. Get the data directly render in EJS template, such benefits are can be done before and after the end of the development of the complete separation, you can put the whole node project to the front end, there is no limit to the back-end technology stack, the front end only need to take the back-end interface. This can be divided into two ways:
- The backend requests a third-party interface, and the data goes straight out to the EJS template
The drawback of this method is obvious, that is, if the interface is loaded too slowly, the whole EJS page will be blank, so this method requires high access speed of the back-end interface.
- in
ejs
The template uses the Ajax request interface directly to fetch the data and render it on the page
This development approach is similar to that of previous yearsweb
Web site development (similar to back-end usejava
Development, front-end injava
In the environmentjsp
In addition to the front-end does not provide back-end interface services, other content has been involved or overall, but the development mode can still achieve the separation of the front and back end, do not need to rely on the back-end development environment.
We made the following changes to app.js:
app.use(async(ctx, Next) => {console.log(ctx.request.path) if (ctx.request.path === '/index') {// home let data = '' await requestDemo().then((body) => { data = JSON.parse(body) }) // ctx.response.status = 200 // ctx.response.body = 'index' await ctx.render('index', } else if (ctx.request.path === '/hello') {// Hello page ctx.response.status = 200 ctx.response.body = 'hello ' world' } else { ctx.throw(404, 'Not found') // 404 } await next() }) async function requestDemo() { let url = 'https://api.douban.com/v2/user/1000001?apikey=0df993c66c0c636e29ecbb5344252a4a' return new Promise(function(resolve, reject) { request(url, function(error, response, body) { if (! error && response.statusCode == 200) { resolve(body); } else {reject(' reject ')}})}); }Copy the code
Json object data (avatar, name, loc_name); now try to insert avatar, name, loc_name attributes in data into index.ejs:
< div > here is the third party interface < a target = "_blank" href = "http://www.doubanapi.com/" > (douban) < / a > request to the data: < br > < div > head: < img SRC = "< % = data. The avatar % >" / > < / div > < div > name: < % = data. The name % > < / div > < div > address: < % = data. The loc_name % > < / div > < / div >Copy the code
The demo sample