


Detailed explanation of the steps to use jade template engine in Node.js
This 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模板文件引用了它们。
现在我们来看这行代码:
res.render('index', {ip: req.ip});
它调用express的Response对象的render方法来渲染模板文件,并且传递了一个本地对象。render方法原型:
res.render(view [, locals] [, callback])
res.render方法渲染一个view并且把渲染生成的HTML字符串发送给客户端。res的API参考在这里http://expressjs.com/4x/api.html。
Response对象也有一个locals对象,它和app.locals的区别是,res的locals只在当前渲染的view内有效,而app.locals是全局的。
另外render方法的可选参数locals,也可以定义本地变量对象,传递给view。我在代码里把ip传了过去。
在jade文件里,常见的有两种方式可以调用由应用程序传入的本地变量:
#{表达式}
标签=表达式
前面的index.jade模板文件里,对于页面标题,我们这么用的:
title= title
title是jade用来定义HTML文档title的标签。
对于body里的一级标题,我们这么用的(h1是jade用来定义HTML一级标题的标签):
h1= title
这都是属于“标签=表达式”这种调用方式,这种方式通常用在一行jade代码的开始,也就是标签开始的地方。而“#{表达式}”这种方式的好处是可以插入到jade模板文件的任意地方。比如:
p Hello, #{ip} p You're the #{counter} visitor.
我们也可以将“h1= title”修改为“h1 #{title}”,效果一样。
jade引擎简介
jade使用一些标签来标记如何生成HTML,jade模板文件看起来很不像HTML文件,但它的模板文件小而整洁。使用jade,需要了解它都支持哪些标签,这个可以直接去看jade-lang,那里最详细也最权威,我们这里只介绍index.jade文件用到的那些标签。
关于jade,有两篇文章不错,可以看看,https://cnodejs.org/topic/5368adc5cf738dd6090060f2和http://www.jb51.net/article/139936.htm,后面这篇文章是网友根号三写的一个关于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”)。
关于jade标签,这篇文章http://www.jb51.net/article/139942.htm说得很好,请参考。
测试jade模板文件
一开始用jade模板,记不全它的标签,也经常不知道自己的写的模板文件生成的html文档是否正确。还好安装jade后,有一个命令行工具jade,可以用来验证模板文件。
jade的用法如下:jade [options] [dir|file …]
jade命令有很多选项,可以执行“jade -h”查看。要验证模板文件,最简单的办法就是使用jade工具生成为html文档。命令如下:
jade xxx.jade
执行上面的命令,就会在当前目录下生成一个与模板文件同名的html文档。不过格式很难读,完全是一坨屎挤在一起。加上 -P(–pretty) 就好了。这样:
jade -P xxx.jade
比如我们有这么一个使用了AngularJS的模板文件scope_template.jade,内容如下:
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文件,内容如下:
<!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="增加")
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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

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

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

Undress AI Tool
Undress images for free

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

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.

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

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

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 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

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).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
