search
HomeWeb Front-endJS TutorialA detailed explanation of getting started with Jade in Node.js

A detailed explanation of getting started with Jade in Node.js

Jun 11, 2018 pm 02:30 PM
nodenodejstemplate engine

This article mainly introduces the detailed introduction to the Node.js template engine Jade. Jade is a template engine for Node.js. Now I will share it with you and give you a reference.

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

1. Tags

In Jade, any text at the beginning of a line is interpreted as an HTML tag by default. And you only need to write the opening tag-note: no need to add "". Because Jade will render the closing and opening tags for us. For example:

body 
  p 
    h1 Jade是Node.js的一个模板引擎
    p  它借鉴了Haml的很多地方,所以语法上和Haml比较相近。
  p 
    footer © Pandora

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

<body>
  <p>
    <h1 id="nbsp-Jade是Node-js的一个模板引擎"> Jade是Node.js的一个模板引擎</h1>
    <p>它借鉴了Haml的很多地方,所以语法上和Haml比较相近。</p>
  </p>
  <p>
    <footer>© Pandora</footer>
  </p>
</body>

Note: If no tag name is written, the default is the p tag.

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= title
p= body

Rendered output HTML:

<h1 id="Express-js-nbsp-Guide">Express.js Guide</h1>
<p>The Comprehensive Book on Express.js</p>

3. Read variables

Reading the value of a variable in Jade is achieved through #{name}. For example:

- var title = "Node"

p I love #{title}

The value of the variable is processed when the template is compiled, so do not use it in executable JavaScript(-).

4. Attributes

The attributes follow the label and are enclosed by "()", and multiple attributes are separated by ",". For example: body (name1 = “value1”, name2 = “value2”).

p(id="content", class=&#39;main&#39;)
  a(href=&#39;http://csdn.net&#39;, title=&#39;csdn主页&#39;, target=&#39;_blank&#39;) CSDN:中国软件联盟
  form(action="/login")
    button(type="submit", value="提交")

Output:

<p id="content" class=&#39;main&#39;>
  <a href=&#39;http://csdn.net&#39; title=&#39;csdn主页&#39; target=&#39;_blank&#39;> CSDN:中国软件联盟</a>
  <form action="/login">
    <button type="submit" value="提交">
  </form>
</p>

Dynamic attributes:

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

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

The data provided to the above template:

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

The HTML output after final rendering:

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

Note: The attribute value of false is used when outputting HTML code will be ignored; when no attribute value is passed in, it will default to true.

5. Literal

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

p#content
  p.lead.center
    | Pandora_galen
    #side-bar.pull-right // 没有标签名,默认为“p”
    span.contact.span4
      a(href="/contact" rel="external nofollow" rel="external nofollow" ) contact me

Rendered output HTML:

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

6, text

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

p 
  | 我两年前开始学习前端
  | 在此之间,我学过了html, jQuery, JavaScript, Python, Css3, HTML5, Bootstrap, D3.js, SVG...而现在我在学Node。并且我已经深深的爱上了前端。

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 .

8. JavaScript code

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

For example, you can use it! =Define an array and output tag data:

- var arr = [&#39;<a>&#39;, &#39;<b>&#39;, &#39;<c>&#39;]
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>

One of the main differences between the template engine Jade and Handlebars is: Jade allows almost all JavaScript to be written in the code ; However, Handlebars limit developers to a small number of built-in and custom helpers.

9. Comments

There are two types of Jade comments:

. Output to the page - "//"
. Not output to the page - "//-"

// 普通注释,会输出到渲染后生成的HTML页面
p Hello Jade content

//- 特殊注释,不会输出到HTML页面
p (id="footer") copyright 2016

Output:

<!-- 普通注释,会输出到渲染后生成的HTML页面 -->
<p> Hello Jade content </p>

<p id="footer">copyright 2016</p>

10, if statement

Add a prefix - to the if statement, so that you can write standard JavaScript code; you can also use it without the prefix or parentheses, of course the latter is more concise.

- var user = {}
- user.admin = Math.random() > 0.5

if user.admin
  button(class = "launch") Launch Spacecraft
else 
  button(class = "login") Log in

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

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

11. Each statement

Iteration in Jade is very simple. Just use the each statement.

- var language = [&#39;JavaScript&#39;, &#39;Node&#39;, &#39;Python&#39;, &#39;Java&#39;]
p
  each value, index in language
    p= index + "," + value

Output:

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

Example 2:

- var language = [&#39;JavaScript&#39;: -1, &#39;Node&#39;: 2, &#39;Python&#39;: 3, &#39;Java&#39;: 1]

p 
  each value, key in languages
    p= key + ":" + value

Output:

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

12, Filter

The function of the filter is: Use another language to write a text block;

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 need to install the Markdown module, as well as 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 sure It won't be unfamiliar, and the usage of mixin in Jade is basically the same as them.

Declaration syntax: mixin name(param, param2, …….)

Call: name(data)

mixin row(items)
  tr
    each item, index in items
      td= item

mixin table(tableData)
  table
    each row, index in tableData
      +row(row)

- var node = [{name: "express"}, {name: "Jade"}, {name: "Handlebars"}]
+table(node)

- var js = [{name: &#39;backbone&#39;}, {name: &#39;angular&#39;}, {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 very similar to introducing JS and CSS external files. It's a top-down approach: in the main file that includes other files, we decide what to use. The main file will be processed first (data locals can be defined in the main file), and then the sub-files included in the main file will be processed (the sub-files can use data locals defined in the main file);

To include a Jade template, use include /path/filename.

For example, in file A:

include ./includes/header

Note: There is no need to add double quotes or single quotes to the template name and path here. .

Another example, start searching from the parent directory:

include ../includes/footer

Note: You cannot use variables in file names and file paths, because includes/partials are processed at compile time, not at execution time .

对于使用Sass、Compass又或者Less的人这些事再熟悉不过的了。

16、extend

extend与include“唱对台戏”,正好相反,extend是一种自底向上的方法。它所包含的文件决定它要替换主文件中哪那一部分。

使用格式: extend filename 和 block blockname;

示例-1: 在文件file_a里:

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

示例-2: 在文件file_b里:

extend file_a
block header
  p very specific text
block content
  .main-content

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在微信小程序中如何才能获取图片信息

在微信小程序中如何实现animation动画

使用百度地图如何去掉marker覆盖物具体该如何解决

在微信小程序中如何获取用户信息(详细教程)

在微信小程序中如何才可以获取用户手机号信息

在Vue中通过header组件如何开发(详细教程)

利用jquery如何写出PC端轮播图(详细教程)

详细讲解有关实现react服务器渲染问题

The above is the detailed content of A detailed explanation of getting started with Jade in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment