Get started with Node. js template engine Jade, node. jsjade

Source: Internet
Author: User

Get started with Node. js template engine Jade, node. jsjade

Jade is a template engine of Node. js. It draws on many aspects of Haml, so its syntax is similar to Haml. In addition, Jade supports spaces.

1. Labels

In Jade, any text starting with a line is interpreted as an HTML Tag by default. And you only need to write the start tag-Note: you do not need to add "<> ". Because Jade will help us render closed and start labels. For example:

Body div h1 Jade is a Node. js template engine p. It draws on many aspects of Haml, so the syntax is similar to Haml. Div footer©Pandora

The final HTML code rendered by the Jade template above is:

<Body> <div> 

Note: If the tag name is not written, the div tag is used by default.

2. Variables/Data

The data passed to the Jade template is called locals. Use the equal sign "=" to output the value of a variable.

(Locals ):

{  title: "Express.js Guide",  body: "The Comprehensive Book on Express.js"}

Jade code:

h1= titlep= body

HTML for rendering output:

3. Read Variables

The value of the read variable in Jade is implemented through # {name. For example:

- var title = "Node"p I love #{title}

When the template is compiled, the variable value is processed. Therefore, do not use it in executable JavaScript.

4. Attributes

Attributes are immediately followed by tags and enclosed by "()". Multiple Attributes are separated. For example, body (name1 = "value1", name2 = "value2 ").

Div (id = "content", class = 'main') a (href = 'HTTP: // csdn.net ', title = 'csdn homepage', target = '_ blank ') CSDN: China Software Alliance form (action = "/login") button (type = "submit", value = "submit ")

Output:

<Div id = "content" class = 'main'> <a href = 'HTTP: // csdn.net 'title = 'csdn homepage 'target =' _ blank '> csdn: china Software Alliance </a> <form action = "/login"> <button type = "submit" value = "submit"> </form> </div>

Dynamic attributes:

Dynamic attribute: the attribute value is dynamic, that is, a variable is used to represent the attribute value. The symbol "|" can be used to write HTML node content in a new line. For example:

a(href=url, data-active=isActive)label  input(type="checkbox", checked=isChecked)  | yes / no

Data provided to the preceding template:

{  url: "/logout",  isActive: true,  isChecked: false}

HTML output after final rendering:

<a href="" data-active=" rel="external nofollow" data-active"></a><label>  <input type="checkbox" />yes / no</label>

Note: If the attribute value is false, the attribute is ignored when HTML code is output. If the attribute value is not input, the default value is true.

5. Literal

To save trouble, you can directly write the class name and ID name after the label name. For example:

Div # content p. lead. center | Pandora_galen # side-bar.pull-right // no label name, the default is "div" span. contact. span4 a (href = "/contact" rel = "external nofollow" rel = "external nofollow") contact me

HTML for rendering output:

<div id="content">  <p class="lead center">  Pandora_galen  <div id="side-bar" class="pull-right"></div>  <span class="contact span4">    <a href="/contact" rel="external nofollow" rel="external nofollow" > contact me </a>  </span></div>

6. Text

Use the '|' symbol to output the original text.

Div | I started learning front-end two years ago. | in the meantime, I learned html, jQuery, JavaScript, Python, Css3, HTML5, Bootstrap, D3.js, SVG... now I am learning Node. And I have fallen in love with the front-end.

7. Script and Style Blocks

Use the "." symbol to create in HTML

script.  console.log("Hello world!");  setTiemout(function() {    window.location.href = "http://csdn.net"  }, 1000);  console.log("Good bye!");

Generated code:

<script>  console.log("Hello world!");  setTiemout(function() {    window.location.href = "http://csdn.net"  }, 1000);  console.log("Good bye!");</script>

Similarly, style generates <style> </style>.

8. JavaScript code

Use-, = or! = These three symbols write executable JS code that can manipulate the output in Jade. This is useful for outputting HTML elements and injecting JavaScript. However, you must be careful to avoid cross-site scripting (XSS) attacks.

For example, it can be used! = Define an array and output tag data:

- var arr = ['<a>', '<b>', '<c>']ul  -for (var i = 0; i < arr.length; i++)    li      span= i      span!= "unescaped:" + arr[i] + "vs."      span= "escaped:" + arr[i]

The generated code is as follows:

<ul>  <li><span>0</span><span>unescaped: <a>vs. </span><span>escaped: <a></span></li>  <li><span>1</span><span>unescaped: <b>vs. </span><span>escaped: <b></span></li>  <li><span>2</span><span>unescaped: <c>vs. </span><span>escaped: <c></span></li></ul>

A major difference between the template engine Jade and Handlebars is that Jade allows almost all JavaScript code. However, handlebars limits developers to use only a small number of built-in and custom helpers.

9. Notes

There are two types of Jade Annotations:

<1>. -- "//" output to the page
<2>. -- "//-" that is not output to the page

// Normal comment, which is output to the rendered HTML page p Hello Jade content //-special comment, not to the HTML page p (id = "footer") copyright 2016

Output:

<! -- Normal comment, which is output to the rendered HTML page --> <p> Hello Jade content </p> <p id = "footer"> copyright 2016 </p>

10. if statement

Add a prefix-to the if statement to write the standard JavaScript code. You can also skip the prefix or parentheses. Of course, the latter is more concise.

- var user = {}- user.admin = Math.random() > 0.5if user.admin  button(class = "launch") Launch Spacecraftelse   button(class = "login") Log in

In addition, there is unless, which is equivalent to not or !.

Note: There is no Semicolon ";" at the end of each line of code.

11. each statement

Iteration in Jade is simple. You only need to use the each statement.

- var language = ['JavaScript', 'Node', 'Python', 'Java']div  each value, index in language    p= index + "," + value

Output:

<div>  <p>0. JavaScript</p>  <p>1. Node</p>  <p>2. Python</p>  <p>3. Java</p></div>

Example 2:

- var language = ['JavaScript': -1, 'Node': 2, 'Python': 3, 'Java': 1]div   each value, key in languages    p= key + ":" + value 

Output:

<div>  <p>JavaScript: -1</p>  <p>Node: 2</p>  <p>Python: 3</p>  <p>Java: 1</p></div>

12. Filter

Filters are used to write a text block in another language;

p  :markdown    # practical Node.js    [This book](http://csdn.net) really helps to grasp many coponents needed for modern-day web development.

Note: To use the Markdown filter, you must install the Markdown module and the Marked and Markdown NPM packages.

13. case

- var coins = Math.round(Math.random() * 10)case coins  when 0    p You have no money  when 1    p You have a coin  default    p You have #{coins} coins!

14. Function mixin

If you have used sass or compass mixin, you are certainly not new, and the use of mixin in Jade is basically the same as that of them.

Statement Syntax: mixin name (param, param2 ,.......)

Call: + name (data)

mixin row(items)  tr    each item, index in items      td= itemmixin table(tableData)  table    each row, index in tableData      +row(row)- var node = [{name: "express"}, {name: "Jade"}, {name: "Handlebars"}]+table(node)- var js = [{name: 'backbone'}, {name: 'angular'}, {name: "emberJS"}]+table(js) 

Output:

<table>  <tr>    <td>express</td>  </tr>  <tr>    <td>Jade</td>  </tr>  <tr>    <td>Handlebars</td>  </tr></table><table>  <tr>    <td>backbone</td>  </tr>  <tr>    <td>angular</td>  </tr>  <tr>    <td>emberJS</td>  </tr></table>

15. include

Include is similar to introducing JS and CSS external files. It is a top-down method: in the main file that includes other files, we decide what to use. The master file will be processed first (you can define the data locals in the master file ), then the sub-files contained in the main file will be processed (locals defined in the main file can be used in the sub-files );

Contains a Jade Template Using include/path/filename.

For example, in file:

include ./includes/header

Note: you do not need to add double quotation marks or single quotation marks to the Template Name and path.

Another example is to start searching from the parent directory:

include ../includes/footer

Note: variables cannot be used in file names and file paths, because des/partials is processed during compilation rather than execution.

I am not familiar with Sass, Compass, or Less.

16. extend

Extend and include are just the opposite. extend is a bottom-up method. The file it contains determines which part of the main file it wants to replace.

Format: extend filename and block blockname;

Example-1: In the file file_a:

block header  p some default textblock content  p loading...block footer  p copyright

Example-2: In File file_ B:

extend file_ablock header  p very specific textblock content  .main-content

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.