A list,
Compared to the Jade template engine, EJS makes no structural changes to the original HTML language, only some modifications to its interactive data, making it much simpler to use than Jade. So the cost of learning is very low. You can also refer to ejS official website: EJs.bootcss.com/
Two, ejS basic use
Here we use the following configuration file:
We can implement basic EJS operations by using app.js files:
const express=require("express");
const ejs=require("ejs");
const fs=require("fs");
var app=express();
/ / reference ejs
app.set('views'."public"); // Set the corresponding directory for the view
app.set("view engine"."ejs"); // Set the default template engine
app.engine('ejs', ejs.__express); // Define the template engine
app.get("/".function(req,res){
res.render("index.ejs", {title: "<h4>express</h4>"});
});
app.listen(8080);
Copy the code
Ejs file:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body><% for(var i=0; i<10; i++){ %> <%= i %> <% } %><! Get variable -->
<div class="datas">
<p>Get variables:</p>
<%- title %>
<%= title %>
</div>
</body>
</html>
Copy the code
In this case, we will get the following result:
From this we can know:
<% XXX %> : inside is written js syntax, <%= XXX %> : inside is sent by the server to ejS template after escaping variables, output as the original HTML <% -xxx %> : It is also a variable sent by the server to the EJS template, but it will output HTML to the <%# comment tag, no execution, no outputCopy the code
The res.render() function also supports callbacks:
res.render('user', { name: 'Tobi' }, function(err, html) {
console.log(html);
});
Copy the code
Then we will see the contents of the HEML. Render (); render file (); render file (); render(); render();
ejs.render(str, data, options);
ejs.renderFile(filename, data, options, function(err, str){
// STR => Outputs the drawn HTML
});
Copy the code
Three, EJS label various meanings
<% 'script' tag, used for process control, no output. <%_ Remove the space before it <%= Output data to the template (output is escaped HTML tags) <%- Output non-escaped data to the template <%# comment tags, No execution, no output <%% Output string '<%' %> General end tag -%> Delete the newline character immediately following _%> deletes the space character following the end tagCopy the code
This is the basic usage of EJS, and then the database operation directly sends the JSON data from the server back to the template engine.
Learn a little bit every day!
Date: 2021/12/2
Learning Reference Video: *www.bilibili.com/video/BV1i7…
Learning Reference document Reference section related video copywriting and courseware, only for personal learning and recording