EJS is what, how to use, and the advantages

Source: Internet
Author: User

First, what is Ejs

Ejs is a JavaScript template library that is used to generate HTML strings from JSON data.

Second, why to use Ejs

Compared to the original JavaScript, some people who don't know your code are more likely to be able to read your code through EJS template code. Let's relax and enjoy the excitement of a clean and concise feeling.

In short, you can make the code more clean and tidy, easy to understand.

You can look at the following example:

This is code implemented in JavaScript.

var html = "

HTML + = "<ul>"

for (var i=0; i<data.supplies.length; i++) {

HTML + = "<li><a href= ' supplies/" +data.supplies[i]+ ">"

HTML + = data.supplies[i]+ "</a></li>"

}

HTML + = "</ul>"

The final effect is to achieve the following

But the code above looks messy, and although it does, it's not easy to get a sense of. Not only is the code ugly, but your HTML structure is completely lost in JavaScript code.

The following learning Ejs also achieve the above effect, it works as follows:

Use Ejs to get back your clear, well-maintained HTML code structure.

Note: Data is a JSON object and cannot be made into a JSON string.

Introduce Ejs in HTML to enable JavaScript to use it, introducing the EJS statement as follows:

<scripttype="text/javascript"src="/js/ejs.js"></script>

Create a Ejs template named Cleaning.ejs file with the following contents:

<ul>  <%  for ( var  i=0; i<supplies.length; i++) { %> 

<li>

  <a href= ‘supplies/<%=supplies[i] %>‘ >

 <%= supplies[i] %>   </a>  

</li>

<% } %></ul>

My HTML documents are as follows, introducing Ejs, and more of our offering Ejs templates to create Ejs objects, and then call Ejs object member functions to parse the JSON object into the template.

<html><head><script type="text/javascript"src="/js/ejs.js"></script><scripttype="text/javascript">function myfunction(){var data=‘{"title":"cleaning","supplies":["mop","broom","duster"]}‘     var html = new EJS({url: ‘/js/tmpl/cleaning.ejs‘}).render(JSON.parse(data));    //JSON.parse(data) 把JSON字符串解析为原生的javascript值。    alert(html);    document.getElementById("div1").innerHTML=html;}</script></head><body><buttononclick="myfunction()">点击</button><divid="div1"></div></ body><html>

From the above example, we can see the basic usage of the Ejs template.

Third, the following describes the following EJS syntax and functions:

1, cache function, can cache the parsed HTML template;

2. <% code%> is used to execute JavaScript code.

<% alert (' Hello World ')%>

3, <%= code%> will code HTML escape;

<p><%= ‘hello world‘ %></p>             注:会把hello world显示在h1中。‘<b>hello world</b>‘%><p><%= ‘hello world‘%></p>             注:会把hello world显示在h1中。 ‘<b>hello world</b>‘%>

4, <%-code%> will not be escaped, this line of code will not be executed, like it is commented, and then display the original HTML. It does not affect the execution of the entire page.

<p><%# ‘hello world‘ %>asd</p>   最后显示asd,及显示原网页

5, support custom tags, such as ' <% ' can use ' {', '%> ' with '} ' instead;


In Ejs, the default closing mark is <%. %>, we can also define our own tags. For example:

App.set ("View options",{                                                                                          " Open ":" {{",                                                                                          "Close": "}}"}); 

6, provide some auxiliary functions, used in the template
1), first, returns the initial element of the array;
2), last, returns the final element of the array;
3), capitalize, returns the first letter capitalized string;
4), downcase, returns the lowercase of the string;
5), UpCase, returns the uppercase of the string;
6), sort, sorted (object.create (obj). Sort ()? );
7), sort_by: ' prop ', sorted in ascending order according to the specified prop attribute;
8), size, returns the length, that is, the long property, not necessarily an array to line;
9), plus:n, plus N, will be converted to number for operation;
10), Minus:n, minus N, will be converted to number for operation;
11), times:n, multiplied by N, will be converted to number for operation;
12), Divided_by:n, divided by N, will be converted to number for operation;
13), join: ' Val ', the array with ' Val ' the most delimiter, to be merged into a string;
14), Truncate:n, intercepts the first n characters, and returns a copy when the length is exceeded
15), Truncate_words:n, gets the first n Word,word in the string to be separated by a space;
16), Replace:pattern,substitution, string substitution, substitution does not provide the substring to be deleted;
17), Prepend:val, if the operand is an array, it is merged, and the string is added Val in front;
18), Append:val, if the operand is an array, the merge is done, and the string is added Val at the back;
19), Map: ' prop ', returns an array of the values in the object array whose properties are prop;
20), reverse, flip array or string;
21), get: ' prop ', get the value of the attribute as ' prop ';
22), JSON, convert to JSON format string

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

Iv. using the Created Ejs template

Generate a Ejs object based on the simulations we wrote earlier

New EJS ({url: '/js/tmpl/cleaning.ejs '})

The object has the following two member functions

1, Ejs.compile (str, options); will return the internally parsed function functions
2, Ejs.render (str, options); Returns the parsed string

The Ejs's render function has two parameters, the first is a string, the second is an optional object, and the data that needs to be rendered, like other JavaScript templates, is included in the option object.

Ejs.render (str,option);      //  Render String  str  &NBSP is generally read through the ReadFile method of the Nodejs file system;        Ejs.render (str,{             data : user_data     //  the data to be rendered           });

Some of the options ' parameters are:
1. Cache: If the parsed template is cached, it needs filename as key;
2, FileName: template file name;
3. The context in which the function executes after scope:complile;
4, Debug: The identity is Debeg State, Debug is true will output the generated function content;
5, Compiledebug: Whether the identity is compiled debug, True will generate the parsing process of tracing information, for debugging;
6, client, the identity is used for browser client run, TRUE returns the parsed function functions that can be run separately;
7, open, code at the beginning of the tag, the default is ' <% ';
8, close, code end tag, default to '%> ';
9. Some of the other variables that are provided when parsing the template.
When used in Express, the options parameter is passed in by Response.render, which contains settings in express and user-supplied variable values.

V. Finally summarize the application site of Ejs

    1. Creating HTML strings with JavaScript as we discussed in the Novice tutorial, the disadvantage of spelling strings in JavaScript is that maintainability is not good. When you put these strings together in JavaScript, it's hard to see what html you're writing \---| A structure that your page shows. Using templates allows you to clearly show your HTML through blank lines and indentation in your code.

    2. WebService-based AJAX Web site development Ejs can receive WebService data sent asynchronously in JSON format, pass this data directly into your template, and insert the results into your page. All you need to do is pass the following code:

3. newEJS({url: ‘comments.ejs‘}).update(‘element_id‘‘/comments.json‘)

4. Program Skin changing function

If you want to give the user the ability to make a page display, Ejs provides a very suitable mechanism. Ejs templates are only executed in the browser, so there is no security risk to your server. You can allow your users to upload ejs templates and their associated style sheets to customize the functionality of your site pages.

EJS is what, how to use, and the advantages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.