


Detailed explanation of the steps to use jade template engine in Node.js
May 22, 2018 am 10:34 AMThis time I will bring you a detailed explanation of the steps for using jade with Node.jstemplate engine, what are the precautions for using jade template engine with Node.js, the following is a practical case, one Get up and take a look.
In "Introduction to Node.js Development - Express Installation and Use", we once used express generator to create a HelloExpress website. The express tool generated the basic directory structure for us. Templates, stylesheets, routers, etc. Although it is just a simple HelloWorld thing, it still contains a lot of content. In order to better understand the usage of the jade template engine supported by Express, this time we provide a manually created small website that can display Visitor's IP and count visits.
Install jade
npm?install?-g?jade
Execute the above command to install globally.
Visitor website
Step 1, create a Visitor directory in the myprojects directory.
Step 2, save the following code in the package.json file:
{ ?"name":?"Visitor", ?"version":?"0.0.0", ?"private":?true, ?"dependencies":?{ ?"express":?"~4.13.1", ?"jade":?"~1.11.0", ?} }
This json file describes some information about our Visitor website, the most important part is the dependencies. We are going to use express and jade.
var?express?=?require('express'); var?app?=?express(); var?counter?=?0; //?view?engine?setup app.set('views',?'./views'); app.set('view?engine',?'jade'); app.engine('jade',?require('jade').express); app.get('/',?function(req,?res)?{ ?counter++; ?app.locals.counter?=?counter.toString(); ?res.render('index',?{ip:?req.ip}); }); app.listen(3000); app.locals.title?=?"Welcome?to?Visitor"; app.locals.counter?=?"0";
The app.js file is the entrance to our website.
Step 4, create a views directory, create a template file index.jade in it, the content is as follows:
doctype?html html ?head ?title=?title ?body ?h1=?title ?p?Hello,?#{ip} ?p?You're?the?#{counter}?visitor.
Step 5, execute "npm install" in the Visitor directory to install rely.
Step 6, execute "node app.js" in the Visitor directory to start the website.
Finally, you can access it in the browser. Just enter "http://localhost:3000" in the address bar. Refresh a few times and you may see the following interface:
This simple Visitor website is different from the previous HelloWorld and HelloExpress. It has some dynamic content. Next let's take a look at how this happens.
express and template engine
#I use the jade template engine in Visitor, similar to ejs and many others, you can visit here Learn about: https://github.com/joyent/node/wiki/Modules.
The template engine uses template files to dynamically generate HTML files. During generation, it can integrate data from the application into HTML files according to certain rules. In this way, we not only avoid the tediousness of manually writing HTML (compared to using templates), but also generate web pages with dynamic content.
Express and Jade are better combined. Let’s take a look at how to configure it.
Express configuration jade
The behavior of the Express server can be controlled through some setting options, which can be controlled through the set(setting, value), enable(setting) and disable(setting) to set. For specific supported settings, you can see here http://expressjs.com/4x/api.html. Our Visitor only uses "view engine" and "views".
The "view engine" option is used to set the engine to be used. The Visitor code is as follows:
app.set('view?engine',?'jade');
The "views" option is used to set the directory where the template file is located. The Visitor code is as follows:
app.set('views',?'./views');
I simply used relative paths here. A better approach is to use the path module and splice them based on the global variable dirname. dirname refers to the directory where the script currently being executed is located. For our Visitor example, it is the directory where app.js is located. The code may look like this:
var?path?=?require('path'); path.join(dirname,?'views');
express will use the corresponding engine according to the extension of the template file by default. For *.jade files, express will internally call the following statement:
app.engine('jade',?require('jade').express);
So, our app.js can actually remove this line of code, and the result will be the same.
Local objects
We can include dynamic data in the template file, which comes from the application. We can use the express object's locals object to store local variables. The following code stores the title and access count:
app.locals.title?=?"Welcome?to?Visitor"; app.locals.counter?=?"0";
jade模板文件里可以直接訪問express對象的locals對象的屬性。我在app.js里設置的title和counter,在index.jade模板文件引用了它們。
現(xiàn)在我們來看這行代碼:
res.render('index',?{ip:?req.ip});
它調(diào)用express的Response對象的render方法來渲染模板文件,并且傳遞了一個本地對象。render方法原型:
res.render(view?[,?locals]?[,?callback])
res.render方法渲染一個view并且把渲染生成的HTML字符串發(fā)送給客戶端。res的API參考在這里http://expressjs.com/4x/api.html。
Response對象也有一個locals對象,它和app.locals的區(qū)別是,res的locals只在當前渲染的view內(nèi)有效,而app.locals是全局的。
另外render方法的可選參數(shù)locals,也可以定義本地變量對象,傳遞給view。我在代碼里把ip傳了過去。
在jade文件里,常見的有兩種方式可以調(diào)用由應用程序傳入的本地變量:
#{表達式}
標簽=表達式
前面的index.jade模板文件里,對于頁面標題,我們這么用的:
title= title
title是jade用來定義HTML文檔title的標簽。
對于body里的一級標題,我們這么用的(h1是jade用來定義HTML一級標題的標簽):
h1= title
這都是屬于“標簽=表達式”這種調(diào)用方式,這種方式通常用在一行jade代碼的開始,也就是標簽開始的地方。而“#{表達式}”這種方式的好處是可以插入到jade模板文件的任意地方。比如:
p?Hello,?#{ip} p?You're?the?#{counter}?visitor.
我們也可以將“h1= title”修改為“h1 #{title}”,效果一樣。
jade引擎簡介
jade使用一些標簽來標記如何生成HTML,jade模板文件看起來很不像HTML文件,但它的模板文件小而整潔。使用jade,需要了解它都支持哪些標簽,這個可以直接去看jade-lang,那里最詳細也最權(quán)威,我們這里只介紹index.jade文件用到的那些標簽。
關(guān)于jade,有兩篇文章不錯,可以看看,https://cnodejs.org/topic/5368adc5cf738dd6090060f2和http://www.jb51.net/article/139936.htm,后面這篇文章是網(wǎng)友根號三寫的一個關(guān)于jade的系列文章的開篇,整個系列里的文章都值得一看。
HTML文檔的開始通常是文檔聲明,對應到jade模板文件里,就是doctype html。還有其它的文檔類型,比如xml,可以寫作doctype xml。更多請參考http://jade-lang.com/reference/doctype/。
jade有很多標簽,用于生成HTML對應的標簽。比如html對應,head對應,body對應,p對應,title對應,這也是我們的index.jade用到的所有標簽了。通常我們在HTML里使用的標簽寫法,去掉尖括號就成了jade里可用的標簽,比如對應jade里的p。
HTML標簽往往可以設置name、id、class等屬性,在jade里,是通過tag(attr=value)這種形式表示的。比如p(class=”view-container”),又比如input(type=”checkbox”)。
關(guān)于jade標簽,這篇文章http://www.jb51.net/article/139942.htm說得很好,請參考。
測試jade模板文件
一開始用jade模板,記不全它的標簽,也經(jīng)常不知道自己的寫的模板文件生成的html文檔是否正確。還好安裝jade后,有一個命令行工具jade,可以用來驗證模板文件。
jade的用法如下:jade [options] [dir|file …]
jade命令有很多選項,可以執(zhí)行“jade -h”查看。要驗證模板文件,最簡單的辦法就是使用jade工具生成為html文檔。命令如下:
jade?xxx.jade
執(zhí)行上面的命令,就會在當前目錄下生成一個與模板文件同名的html文檔。不過格式很難讀,完全是一坨屎擠在一起。加上 -P(–pretty) 就好了。這樣:
jade?-P?xxx.jade
比如我們有這么一個使用了AngularJS的模板文件scope_template.jade,內(nèi)容如下:
doctype?html html(ng-app="myApp") ?head ?title=?title ?link(rel='stylesheet',?href='/stylesheets/style.css') ?body ?p(ng-controller="SimpleTemplate") ?|?ValueA:? ?input(type="number"?ng-model="valueA") ?br ?|?ValueB:? ?input(type="number"?ng-model="valueB") ?br ?br ?|?Expression?Value:?{{valueA?+?valueB}} ?br ?br ?input(type="button"?ng-click="addValues(valueA,?valueB)"?value="Click?to?Add?Values?{{valueA}}?&?{{valueB}}") ?br ?|?Clicked?Value:?{{valueC}} ?br ?script(src="/javascripts/angular-1.4.3.min.js") ?script(src="/javascripts/scope_template.js")
運行“jade -P scope_template.jade”命令會生成scope_template.html文件,內(nèi)容如下:
<!DOCTYPE html> <html ng-app="myApp"> ?<head> ?<title></title> ?<link rel="stylesheet" href="/stylesheets/style.css" rel="external nofollow" > ?</head> ?<body> ?<p ng-controller="SimpleTemplate">ValueA:? ?<input type="number" ng-model="valueA"><br>ValueB:? ?<input type="number" ng-model="valueB"><br><br>Expression?Value:?{{valueA?+?valueB}}<br><br> ?<input type="button" ng-click="addValues(valueA, valueB)" value="Click to Add Values {{valueA}} & {{valueB}}"><br>Clicked?Value:?{{valueC}}<br> ?</p> ?<script src="/javascripts/angular-1.4.3.min.js"></script> ?<script src="/javascripts/scope_template.js"></script> ?</body> </html>
需要提一下,我們既可以用jade編寫完整的HTML文檔,也可以編寫符合HTML語法的局部模板。比如下面的jade文件:
p(class="admin-user") ?p?添加用戶 ?table ?tr ?td ?label?用戶名: ?td ?input(type="text"?name="add_username") ?tr ?td ?label?密碼: ?td ?input(type="text"?name="add_password")? ?tr ?td(colspan='2'?align="right") ?input(type="submit"?value="增加")
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注php中文網(wǎng)其它相關(guān)文章!
推薦閱讀:
The above is the detailed content of Detailed explanation of the steps to use jade template engine in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
