Express使用html模板的兩種方式swig,ejs

一。swigcss

/*app.js
應用(啓動)入口文件
*/

//加載express模塊
var express = require('express');
//加載模板處理模塊
var swig = require('swig');
//加載數據庫模塊
var mongoose = require("mongoose");
//加載body-parser,用來處理post提交過來的數據
var bodyParser = require('body-parser');
//加載cookies模塊
var Cookies = require("cookies");
//建立app應用 => NodeJS Http.createServer()
var app = express();

var User = require('./models/User');

//設置靜態文件託管
//當用戶訪問的url以 /public 開始,那麼直接返回對應的__dirname + '/public' 下的文件
app.use('/public', express.static(__dirname + '/public'));

//配置應用模板
//定義當前應用所使用的模板引擎
//第一個參數:模板引擎的名稱,同時也是模板文件的後綴,第二個參數表示用於解析處理模板內容的方法
app.engine('html', swig.renderFile);
//設置模板文件存放的目錄,第一個參數是views,第二個參數是目錄
app.set('views', './views');
//註冊所使用的模板引擎,第一個參數必須是 view engine ,第二個參數是app.engine
//這個方法定義的模板引擎的名稱(第一個參數)是一致的
app.set('view engine', 'html');
//在開發過程當中,須要取消模板緩存
swig.setDefaults({cache: false});

//bodyparser設置
app.use(bodyParser.urlencoded({extended:true}));

//設置cookie
app.use(function(req,res, next){
    req.cookies = new Cookies(req,res);
    req.userInfo={};
    //解析登陸用戶的cookie信息
    if (req.cookies.get('userInfo')){
        try{
            req.userInfo = JSON.parse(req.cookies.get('userInfo'));
            
            
            //獲取當前登陸用戶的類型,是不是管理員
            User.findById(req.userInfo._id).then(function(userInfo){
                req.userInfo.isAdmin = boolean(userInfo.isAdmin);
                //上面哪一個語句很差用,用下面的編寫一個代替吧
                // req.userInfo.isAdmin = false;
                next();
            })
        }catch(e){
            next();
        }
    }
    // console.log(req.cookies.get('userInfo'));
    next();
})

//根據不一樣的功能劃分模塊
app.use('/admin', require('./routers/admin'));
app.use('/api', require('./routers/api'));
app.use('/', require('./routers/main'));






/*
首頁
    req request對象
    res response對象
    next 函數
*/
// app.get('/',function(req, res, next){
//     // res.send('<h1>歡迎光臨個人博客<h1>');
//     /*
//     讀取views目錄下的指定文件,解析並返回給客戶端
//     第一個參數:表示模板的文件,相對於views目錄 views/index.html
//     第二個參數:傳遞給模板使用的數據
//     */
//     res.render('index');
// })

/*這種設置css的方式太麻煩了,實際操做不須要,只是在這裏演示一下.
app.get('/main.css', function(req, res, next){
    res.setHeader('content-type', 'text/css');
    res.send("body{background:red;}");
})
*/

//監聽http請求
mongoose.connect('mongodb://localhost:27018/blog',function(err){
    if(err){
        console.log(err);
        console.log('數據庫鏈接失敗!');
    }else{
        console.log("數據庫鏈接成功!");
        app.listen(8081);
    }
});

//用戶發送http請求 -> url -> 解析路由 -> 找到匹配的規則 -> 執行指定綁定函數,返回對應內容至用戶
//    /public -> 靜態文件 -> 直接讀取指定目錄下的文件,返回給用戶
//  使用路由方式 -> 動態文件 -> 處理業務邏輯,記載模板,解析模板 -> 返回數據給用戶

語法:{{ title }}html

學習swig:node

Swig 使用指南
1、如何使用
一、API
swig.init({
    allowErrors: false,
    autoescape: true,
    cache: true,
    encoding: 'utf8',
    filters: {},
    root: '/',
    tags: {},
    extensions: {},
    tzOffset: 0
});
options:

allowErrors: 默認值爲 false。將全部模板解析和編譯錯誤直接輸出到模板。若是爲 true,則將引起錯誤,拋出到 Node.js 進程中,可能會使您的應用程序崩潰。
autoescape: 默認true,強烈建議保持。字符轉換表請參閱轉義過濾器。
true: HTML安全轉義
false: 不轉義,除非使用轉義過濾器或者轉義標籤
'js': js安全轉義
cache: 更改成 false 將從新編譯每一個請求的模板的文件。正式環境建議保持true。
encoding: 模板文件編碼
root: 須要搜索模板的目錄。若是模板傳遞給 swig.compileFile 絕對路徑(以/開頭),Swig不會在模板root中搜索。若是傳遞一個數組,使用第一個匹配成功的數組項。
tzOffset: 設置默認時區偏移量。此設置會使轉換日期過濾器會自動的修正相應時區偏移量。
filters:自定義過濾器或者重寫默認過濾器,參見自定義過濾器指南。
tags: 自定義標籤或者重寫默認標籤,參見自定義標籤指南。
extensions: 添加第三方庫,能夠在編譯模板時使用,參見參見自定義標籤指南。
二、nodejs
var tpl = swig.compileFile("path/to/template/file.html");
var renderedHtml = tpl.render({ vars: 'to be inserted in template' });
或者

var tpl = swig.compile("Template string here");
var renderedHtml = tpl({ vars: 'to be inserted in template' });
三、結合Express
npm install express
npm install consolidate
而後

app.engine('.html', cons.swig);
app.set('view engine', 'html');
四、瀏覽器
Swig瀏覽器版本的api基本與nodejs版相同,不一樣點以下:

不能使用swig.compileFile,瀏覽器沒有文件系統
你必須提早使用swig.compile編譯好模板
按順序使用extends, import, and include,同時在swig.compile裏使用參數templateKey來查找模板
var template = swig.compile('<p>{% block content %}{% endblock %}</p>', { filename: 'main' });
var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}', { filename: 'mypage' });
2、基礎
一、變量
{{ foo.bar }}
{{ foo['bar'] }}
若是變量未定義,輸出空字符。

變量能夠經過過濾器來修改:

{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
// Jane was born on July 6th, 1985
二、邏輯標籤
參見標籤部分。

三、註釋
四、空白
模板裏的空白在最終輸出時默認保留,若是須要去掉空白,能夠在邏輯標籤先後加上空白控制服-:

{% for item in seq -%}
    {{ item }}
{%- endfor %}
3、模板繼承
Swig 使用 extends 和 block 來實現模板繼承 layout.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{% block title %}My Site{% endblock %}</title>
    {% block head %}
        <link rel="stylesheet" href="main.css">
    {% endblock %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
index.html

{% extends 'layout.html' %}
{% block title %}My Page{% endblock %}
{% block head %}
{% parent %}
    <link rel="stylesheet" href="custom.css">
{% endblock %}
{% block content %}
    <p>This is just an awesome page.</p>
{% endblock %}
4、變量過濾器
用於修改變量。變量名稱後用 | 字符分隔添加過濾器。您能夠添加多個過濾器。

一、例子
{{ name|title }} was born on {{ birthday|date('F jS, Y') }}
and has {{ bikes|length|default("zero") }} bikes.
也可使用 filter 標籤來爲塊內容添加過濾器

{% filter upper %}oh hi, paul{% endfilter %}
二、內置過濾器
add(value):使變量與value相加,能夠轉換爲數值字符串會自動轉換爲數值。
addslashes:用 \ 轉義字符串
capitalize:大寫首字母
date(format[, tzOffset]):轉換日期爲指定格式
format:格式
tzOffset:時區
default(value):默認值(若是變量爲undefined,null,false)
escape([type]):轉義字符
默認: &, <, >, ", '
js: &, <, >, ", ', =, -, ;
first:返回數組第一個值
join(glue):同[].join
json_encode([indent]):相似JSON.stringify, indent爲縮進空格數
last:返回數組最後一個值
length:返回變量的length,若是是object,返回key的數量
lower:同''.toLowerCase()
raw:指定輸入不會被轉義
replace(search, replace[, flags]):同''.replace
reverse:翻轉數組
striptags:去除html/xml標籤
title:大寫首字母
uniq:數組去重
upper:同''.toUpperCase
url_encode:同encodeURIComponent
url_decode:同decodeURIComponemt
三、自定義過濾器
建立一個 myfilter.js 而後引入到 Swig 的初始化函數中

swig.init({ filters: require('myfilters') });
在 myfilter.js 裏,每個 filter 方法都是一個簡單的 js 方法,下例是一個翻轉字符串的 filter:

exports.myfilter = function (input) {
    return input.toString().split('').reverse().join('');
};
你的 filter 一旦被引入,你就能夠向下面同樣使用:

{{ name|myfilter }}
     {% filter myfilter %}
    I shall be filtered
{% endfilter %}
你也能夠像下面同樣給 filter 傳參數:

exports.prefix = function(input, prefix) {
    return prefix.toString() + input.toString();
};
{{ name|prefix('my prefix') }}
{% filter prefix 'my prefix' %I will be prefixed with "my prefix".{% endfilter %}
{% filter prefix foo %}I will be prefixed with the value stored to `foo`.{% endfilter %}
5、標籤
一、內置標籤
extends:使當前模板繼承父模板,必須在文件最前

參數file:父模板相對模板 root 的相對路徑 block:定義一個塊,使之能夠被繼承的模板重寫,或者重寫父模板的同名塊
參數name:塊的名字,必須以字母數字下劃線開頭 parent:將父模板中同名塊注入當前塊中 include:包含一個模板到當前位置,這個模板將使用當前上下文
參數file: 包含模板相對模板 root 的相對路徑
參數ignore missing:包含模板不存在也不會報錯
參數with x:設置 x 至根上下文對象以傳遞給模板生成。必須是一個鍵值對
參數only:限制模板上下文中用 with x 定義的參數
{% include template_path %}
{% include "path/to/template.js" %}
你能夠標記 ignore missing,這樣若是模板不存在,也不會拋出錯誤

{% include "foobar.html" ignore missing %}
本地聲明的上下文變量,默認狀況不會傳遞給包含的模板。例如如下狀況,inc.html 沒法獲得 foo 和 bar

{% set foo = "bar" %}
{% include "inc.html" %}
{% for bar in thing %}
    {% include "inc.html" %}
{% endfor %}
若是想把本地聲明的變量引入到包含的模板種,可使用 with 參數來把後面的對象建立到包含模板的上下文中

{% set foo = { bar: "baz" } %}
{% include "inc.html" with foo %}
{% for bar in thing %}
    {% include "inc.html" with bar %}
{% endfor %}
若是當前上下文中 foo 和 bar 可用,下面的狀況中,只有 foo 會被 inc.html 定義

{% include "inc.html" with foo only %}
only 必須做爲最後一個參數,放在其餘位置會被忽略

raw:中止解析標記中任何內容,全部內容都將輸出

參數file: 父模板相對模板 root 的相對路徑 for:遍歷對象和數組
參數x:當前循環迭代名
參數in:語法標記
參數y:可迭代對象。可使用過濾器修改
{% for x in y %}
    {% if loop.first %}<ul>{% endif %}
        <li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>
    {% if loop.last %}</ul>{% endif %}
{% endfor %}
特殊循環變量

loop.index:當前循環的索引(1開始)
loop.index0:當前循環的索引(0開始)
loop.revindex:當前循環從結尾開始的索引(1開始)
loop.revindex0:當前循環從結尾開始的索引(0開始)
loop.key:若是迭代是對象,是當前循環的鍵,不然同 loop.index
loop.first:若是是第一個值返回 true
loop.last:若是是最後一個值返回 true
loop.cycle:一個幫助函數,以指定的參數做爲週期 ```
{% for item in items %}
    <li class="{{ loop.cycle('odd', 'even') }}">{{ item }}</li>
{% endfor %}
在 for 標籤裏使用 else

{% for person in people %}
    {{ person }}
{% else %}
    There are no people yet!
{% endfor %}
if:條件語句

參數:接受任何有效的 JavaScript 條件語句,以及一些其餘人類可讀語法
{% if x %}{% endif %}
{% if !x %}{% endif %}
{% if not x %}{% endif %}
{% if x and y %}{% endif %}
{% if x && y %}{% endif %}
{% if x or y %}{% endif %}
{% if x || y %}{% endif %}
{% if x || (y && z) %}{% endif %}
{% if x [operator] y %}
    Operators: ==, !=, <, <=, >, >=, ===, !==
{% endif %}
{% if x == 'five' %}
    The operands can be also be string or number literals
{% endif %}
{% if x|length === 3 %}
    You can use filters on any operand in the statement.
{% endif %}
{% if x in y %}
    If x is a value that is present in y, this will return true.
{% endif %}
else 和 else if

{% if foo %}
    Some content.
{% else if "foo" in bar %}
    Content if the array `bar` has "foo" in it.
{% else %}
    Fallback content.
{% endif %}
autoescape:改變當前變量的自動轉義行爲

參數on:當前內容是否轉義
參數type:轉義類型,js 或者 html,默認 html
假設

some_html_output = '<p>Hello "you" & \'them\'</p>';
而後

{% autoescape false %}
    {{ some_html_output }}
{% endautoescape %}
{% autoescape true %}
    {{ some_html_output }}
{% endautoescape %}
{% autoescape true "js" %}
    {{ some_html_output }}
{% endautoescape %}
將會輸出

<p>Hello "you" & 'them'</p>
 &lt;p&gt;Hello &quot;you&quot; &amp; &#39;them&#39; &lt;/p&gt;
 \u003Cp\u003EHello \u0022you\u0022 & \u0027them\u0027\u003C\u005Cp\u003E
set:設置一個變量,在當前上下文中複用

參數name:變量名
參數=:語法標記
參數value:變量值
{% set foo = [0, 1, 2, 3, 4, 5] %} {% for num in foo %}
    <li>{{ num }}</li>
{% endfor %}
macro:建立自定義可服用的代碼段

參數...: 用戶定義
{% macro input type name id label value error %}
 <label for="{{ name }}">{{ label }}</label>
 <input type="{{ type }}" name="{{ name }}" id="{{ id }}" value="{{ value }}"{% if error %} class="error"{% endif %}>
{% endmacro %}
而後像下面使用

<div>
    {{ input("text", "fname", "fname", "First Name", fname.value, fname.errors) }}
</div>
<div>
    {{ input("text", "lname", "lname", "Last Name", lname.value, lname.errors) }}
</div>
輸出以下

<div>
    <label for="fname">First Name</label>
    <input type="text" name="fname" id="fname" value="Paul">
</div>
<div>
    <label for="lname">Last Name</label>
    <input type="text" name="lname" id="lname" value="" class="error">
</div>
import:容許引入另外一個模板的宏進入當前上下文

參數file:引入模板相對模板 root 的相對路徑
參數as:語法標記 var: 分配給宏的可訪問上下文對象
{% import 'formmacros.html' as form %}
{# this will run the input macro #}
    {{ form.input("text", "name") }}
    {# this, however, will NOT output anything because the macro is scoped to the "form"     object: #}
{{ input("text", "name") }}
filter:對整個塊應用過濾器

參數filter_name: 過濾器名字
參數... : 若干傳給過濾器的參數 父模板相對模板 root 的相對路徑
{% filter uppercase %}
    oh hi, {{ name }}
{% endfilter %}
{% filter replace "." "!" "g" %}
    Hi. My name is Paul.
{% endfilter %}
輸出

OH HI, PAUL Hi! My name is Paul!
spaceless:嘗試移除html標籤間的空格

{% spaceless %}
    {% for num in foo %}
        <li>{{ loop.index }}</li>
    {% endfor %}
{% endspaceless %}
輸出

<li>1</li><li>2</li><li>3</li>

 

 

 

二。ejsmongodb

/*app.js
*/
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');  //我是新引入的ejs插件

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine("html", ejs.__express);
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

 

(1)配置方法:數據庫

npm install ejs

var ejs = require('ejs');  
app.engine('html', ejs.__express);
app.set('view engine', 'html');

語法: <%= title %>express

學習:能夠去ejs官網          https://ejs.bootcss.com/ npm

簡略學習:json

入門
安裝
利用 NPM 安裝 EJS 很簡單。

$ npm install ejs
Use
將模板字符串和一些數據做爲參數傳遞給 EJS,Duang,HTML 出來了。

var ejs = require('ejs'),
    people = ['geddy', 'neil', 'alex'],
    html = ejs.render('<%= people.join(", "); %>', {people: people});
瀏覽器支持
從這裏下載 最新的瀏覽器版本,而後引入頁面便可。

<script src="ejs.js"></script>
<script>
  var people = ['geddy', 'neil', 'alex'],
      html = ejs.render('<%= people.join(", "); %>', {people: people});
</script>
文檔
實例
<% if (user) { %>
  <h2><%= user.name %></h2>
<% } %>
用法
var template = ejs.compile(str, options);
template(data);
// => 輸出繪製後的 HTML 字符串

ejs.render(str, data, options);
// => 輸出繪製後的 HTML 字符串

ejs.renderFile(filename, data, options, function(err, str){
    // str => 輸出繪製後的 HTML 字符串
});
參數
cache 緩存編譯後的函數,須要提供 filename
filename 被 cache 參數用作鍵值,同時也用於 include 語句
context 函數執行時的上下文環境
compileDebug 當爲 false 時不編譯調試語句
client 返回獨立的編譯後的函數
delimiter 放在角括號中的字符,用於標記標籤的開與閉
debug 將生成的函數體輸出
_with 是否使用 with() {} 結構。若是爲 false,全部局部數據將存儲在 locals 對象上。
localsName 若是不使用 with ,localsName 將做爲存儲局部變量的對象的名稱。默認名稱是 locals
rmWhitespace 刪除全部可安全刪除的空白字符,包括開始與結尾處的空格。對於全部標籤來講,它提供了一個更安全版本的 -%> (在一行的中間並不會剔除標籤後面的換行符)。
escape 爲 <%= 結構設置對應的轉義(escape)函數。它被用於輸出結果以及在生成的客戶端函數中經過 .toString() 輸出。(默認轉義 XML)。
標籤含義
<% '腳本' 標籤,用於流程控制,無輸出。
<%_ 刪除其前面的空格符
<%= 輸出數據到模板(輸出是轉義 HTML 標籤)
<%- 輸出非轉義的數據到模板
<%# 註釋標籤,不執行、不輸出內容
<%% 輸出字符串 '<%'
%> 通常結束標籤
-%> 刪除緊隨其後的換行符
_%> 將結束標籤後面的空格符刪除
包含(include)
經過 include 指令將相對於模板路徑中的模板片斷包含進來。(須要提供 'filename' 參數。) 例如,若是存在 "./views/users.ejs" 和 "./views/user/show.ejs" 兩個模板文件,你能夠經過 <%- include('user/show'); %> 代碼包含後者。

你可能須要可以輸出原始內容的標籤 (<%-) 用於 include 指令,避免對輸出的 HTML 代碼作轉義處理。

<ul>
  <% users.forEach(function(user){ %>
    <%- include('user/show', {user: user}); %>
  <% }); %>
</ul>
自定義分隔符
可針對單個模板或全局使用自定義分隔符:

var ejs = require('ejs'),
    users = ['geddy', 'neil', 'alex'];

// 單個模板文件
ejs.render('<?= users.join(" | "); ?>', {users: users},
    {delimiter: '?'});
// => 'geddy | neil | alex'

// 全局
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'