Getting started with ejs

1. What is EJS?

  What does "E" stand for? It can mean "Embedded", "Effective", "Elegant" or "Easy". EJS is a simple template language that helps you generate HTML pages with ordinary JavaScript code. EJS has no dogma on how to organize content; nor has it reinvented a set of iteration and control flow syntax; some are just ordinary JavaScript code.

2. Why use EJS?

   Compared with the original JavaScript, some people who don't know your code can understand your code more easily through EJS template code. Let us relax and enjoy the exciting clean and concise feeling together.
   In short, it can make the code cleaner and easier to understand.

Three, the use of ejs

1. Use npm to install ejs

$ npm install ejs

2. Introduce ejs module

const ejs = require('ejs');

Fourth, the following describes the syntax and functions of EJS:

1. Cache function, can cache the parsed html template;

2. <% code %> is used to execute the javascript code. (The file suffix changed from .js to .ejs)

<% alert('hello world') %>

3. <%= code %> will html escape the code;

<h1><%=title %></h1>                    注:会把title里面存的值给显示出来在h1中。
<p><%= 'hello world' %></p>             注:会把hello world显示在p中。
<h1><%= '<b>hello world</b>' %></h1>    注:会把<b>hello world</b>显示在h1中。

4. Support custom tags, for example,'<%' can be replaced with'{ {','%>' can be replaced with'}}'; in
   ejs, the default closing tag is <%… %>, and we can also define our own label. E.g:

if, else 条件语句的使用

    < div class="login"> 

           <% if (user.uid.length > 0) {
    
     %>

           <a href="#"><%= user.uid%></a><a href="#"><i class="caret down icon"></i></a>

           <% } else {
    
     %>

           <a href="#">Login</a>

           <% } %>

        </div>

         后台路由中要把数据传递进来,即:res.render('list',{
    
    user: {
    
    uid:'xxx'}});


5. Use <%- include filename %> to load other page templates;

Five, parameters

1. cache Compiled functions will be cached, filename is required

2. The filename is used by the cache as a cache key to contain

3. The context in which the context function is executed

4. If compileDebug is false, tools for debugging will not be compiled

5. The client returns an independent compiled function

6. delimiter The characters used to open or close angle brackets

7. Debug output generated function body

8. Does _with use with() {} structure. If false, local data will be stored in the locals object.

9. rmWhitespace removes all whitespace characters that can be safely removed, including leading and trailing whitespace characters. At the same time, a safer mode of -%> line break truncation is turned on for all scriptlet tags. (It will not remove the newline of the label in a line).

Guess you like

Origin blog.csdn.net/qq_45954445/article/details/108911711