Home  >  Article  >  Web Front-end  >  How to operate Node.js using jade template engine

How to operate Node.js using jade template engine

php中世界最好的语言
php中世界最好的语言Original
2018-05-30 11:20:181624browse

This time I will show you how to operate Node.js using jadetemplate engine, what are the precautions for operating Node.js using jade template engine, the following is a practical case, Let’s 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文件里,常见的有两种方式可以调用由应用程序传入的本地变量:

  1. #{表达式}

  2. 标签=表达式

前面的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中文网其它相关文章!

推荐阅读:

怎样进行Vue拖拽组件开发

怎样使用node前端模板引擎Jade标签

The above is the detailed content of How to operate Node.js using jade template engine. 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