Getting Started with node. JS Development-Using the Jade template engine

Source: Internet
Author: User

In the "Getting Started with node. JS Development--express Installation and use" We used to create a helloexpress website using Express generator, which generated the basic directory structure, templates, stylesheet, Routers and so on. Although it is just a simple HelloWorld class of small things, but it contains a lot of content, in order to better understand the use of the Jade template engine supported by express, we provide a manually created small website, can display the IP of the visitors, and count the access.

Install Jade

NPM install-g Jade

Perform the above command, global installation.

Visitor website

1th Step , create a visitor directory under the MyProjects directory.

2nd Step , 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 of the information about our visitor website, and the most important part is dependency. We want to use Express and Jade.

3rd Step , save the following code to the App.js file:

var express = require(‘express‘);var app = express();var counter = 0;// view engine setupapp.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";

App.js file is the entrance to our website.

The 4th step , create a views directory, create a template file inside the Index.jade, the contents are as follows:

doctype htmlhtml  head    title= title  body    h1= title    p Hello, #{ip}    p You‘re the #{counter} visitor.

The 5th step is to perform "NPM install" in the Visitor directory and install dependencies.

6th step , execute "node App.js" in the visitor directory, start the website.

Finally, it can be accessed in the browser, the Address bar type "http://localhost:3000" can be refreshed several times, you may see the following interface:

This simple visitor site, and the previous HelloWorld, helloexpress are not quite the same, it has some dynamic content. And then we'll see how it all happened.

Express and Template engine

I used the Jade template engine in the visitor, similar to the Ejs and many, can be accessed here to understand: https://github.com/joyent/node/wiki/Modules#templating.

The template engine uses template files to dynamically generate HTML files that, when generated, can be incorporated into an HTML file in accordance with certain rules. In this way, we avoid the tedious use of manual html (relative to templates) and the ability to generate Web pages with dynamic content.

Express and Jade combine well, let's see how to configure it.

Express Configuration Jade

The behavior of the express server can be controlled by a set of options that can be set by the Express object's set (setting, value), enable (setting), and disable (setting). Specific support for which settings, you can see here http://expressjs.com/4x/api.html#app.settings.table. Our visitor only use "View engine" and "views".

The "View Engine" option is used to set the engine to use, and the visitor code is as follows:

app.set(‘view engine‘, ‘jade‘);

The "views" option is used to set the directory where the template files are located, visitor code is as follows:

app.set(‘views‘, ‘./views‘);

I'm simply using a relative path here, and a better approach is to use the path module to __dirname the global variable. __dirname refers to the directory where the script is currently executing, and to our visitor example, the directory where the App.js is located. The code might be like this:

var path = require(‘path‘);path.join(__dirname, ‘views‘);

By default, Express uses the corresponding engine based on the extension of the template file. For the *.jade file, the following statement is called Inside Express:

app.engine(‘jade‘, require(‘jade‘).__express);

So, our app.js can actually get rid of this line of code, and the result is the same.

Local objects

We can include dynamic Data in the template file, which comes from the application. We can use the locals object of the Express object to store local variables. The following code stores the header and access count:

app.locals.title = "Welcome to Visitor";app.locals.counter = "0";

The properties of the locals object of the Express object can be accessed directly in the Jade template file. I set the title and counter in App.js, and referenced them in the Index.jade template file.

Now let's look at this line of code:

  res.render(‘index‘, {ip: req.ip});

It invokes the Render method of Express's response object to render the template file, and passes a local object. Render Method Prototypes:

res.render(view [, locals] [, callback])

The Res.render method renders a view and sends the rendered HTML string to the client. The Res API reference is http://expressjs.com/4x/api.html#res here.

The response object also has a locals object, which differs from app.locals in that the locals of RES is only valid within the currently rendered view, and App.locals is global.

Alternatively, the optional parameter of the Render method is locals, and the local variable object can be defined and passed to the view. I passed the IP over the code.

In the jade file, there are two common ways to invoke local variables that are passed in by the application:

    1. #{-expression}
    2. label = Expression

In the previous Index.jade template file, for the page title, we used this:

title= Title

Title is the label that Jade uses to define the title of the HTML document.

For the first-level title in the body, we use this (H1 is the label that Jade uses to define HTML-level headings):

h1= Title

This is called the "label = Expression" method, which is usually used at the beginning of a line of jade Code, where the label begins. The benefit of the "#{expression}" approach is that it can be inserted anywhere in the jade template file. Like what:

    p Hello, #{ip}    p You‘re the #{counter} visitor.

We can also modify "h1= title" to "H1 #{title}", the same effect.

About Jade Engine

Jade uses some tags to mark how the generated html,jade template file does not look like an HTML file, but its template file is small and neat. With Jade, you need to know which tags it supports, this can go straight to the Jade-lang, where the most detailed and authoritative, we only introduce those tags used in index.jade files.

About Jade, there are two articles good, can see, HTTPS://CNODEJS.ORG/TOPIC/5368ADC5CF738DD6090060F2 and http://www.html-js.com/article/ 2570, the following article is a netizen root three wrote a series of articles about Jade, the opening of the whole series of articles are worth a look.

The beginning of the HTML document is usually the document declaration, which corresponds to the DOCTYPE HTML in the Jade template file. There are other types of documents, such as XML, that can be written doctype XML. Please refer to http://jade-lang.com/reference/doctype/for more information.

Jade has a number of tags that are used to generate HTML-corresponding tags. such as HTML correspondence, head corresponding, body corresponding, p corresponding

, title corresponds, and this is all the tags that our index.jade used. Usually the tags we use in HTML are written, and the angle brackets are removed as the available tags in jade, such as the Div in Jade.

HTML tags can often be set to name, ID, class and other attributes, in Jade, is through the form of tag (Attr=value) is expressed. such as Div (class= "View-container"), such as input (type= "checkbox").

About the Jade label, this article http://www.html-js.com/article/2575 very well, please refer to. And this article http://iammr.7.blog.163.com/blog/static/49102699201391625916658/, also good.

Test the Jade template file

Start with the jade template, not all its tags, also often do not know their own writing template file generated HTML document is correct. Fortunately after installing Jade, there is a command line tool, Jade, that can be used to validate template files.

The usage of Jade is as follows:

Jade [options] [dir|file ...]

The Jade command has many options to perform "jade-h" viewing. The simplest way to validate a template file is to use the Jade tool to become an HTML document. The command is as follows:

jade xxx.jade

By executing the above command, an HTML document with the same name as the template file is generated in the current directory. But the format is very difficult to read, it is a lump of excrement squeezed together. Plus-P (–pretty) is good. Such

jade -P xxx.jade

For example, we have a template file that uses the Angularjs Scope_template.jade, which reads as follows:

doctype htmlhtml(ng-app="myApp")  head    title= title    link(rel=‘stylesheet‘, href=‘/stylesheets/style.css‘)  body    div(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")

Running the "jade-p scope_template.jade" command generates a scope_template.html file with the following contents:

<!DOCTYPE html>

It is necessary to mention that we can either write a complete HTML document with jade or write a local template that conforms to the HTML syntax. For example, the following jade file:

div(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="增加")

Other articles:

    • node. JS Development Starter--express Routing and middleware
    • node. JS Development Primer--express Installation and use
    • node. JS Development Primer--http File Server
    • node. JS Development Primer--helloworld Re-analysis
    • Introduction to node. JS Development--Environment building and HelloWorld

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Getting Started with node. JS Development-Using the Jade template engine

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.