Express - 动态网页模板(四)

文章推荐

Express-官方文档
Express-菜鸟教程
阮一峰博客-Express
案例代码github

文件目录.png

// blog.js
var entries = [{
        "id": 1,
        "title": "第一篇",
        "body": "正文",
        "published": "6/2/2013"
    },
    {
        "id": 2,
        "title": "第二篇",
        "body": "正文",
        "published": "6/3/2013"
    },
    {
        "id": 3,
        "title": "第三篇",
        "body": "正文",
        "published": "6/4/2013"
    },
    {
        "id": 4,
        "title": "第四篇",
        "body": "正文",
        "published": "6/5/2013"
    },
    {
        "id": 5,
        "title": "第五篇",
        "body": "正文",
        "published": "6/10/2013"
    },
    {
        "id": 6,
        "title": "第六篇",
        "body": "正文",
        "published": "6/12/2013"
    }
]
exports.getBlogEntries = function () {
    return entries;
}
exports.getBlogEntry = function (id) {
    for (var i = 0; i < entries.length; i++) {
        if (entries[i].id == id)
            return entries[i]
    }
}
// app.js
var express = require('express');
var app = express();
/*
    hbs是模板引擎,express支持多种模板引擎
        安装 npm i hbs --save-dev
*/
var hbs = require('hbs');           // 加载hbs模块
/*
    bodyParser - node.js中间件,用于处理JSON,Raw,Text和URL编码数据
*/
var bodyParser = require('body-parser');

// 加载数据
var blogEngine = require('./blog');

app.set('view engine','html')       // 指定模板文件的后缀名为html
app.engine('html',hbs.__express);   // 运行hbs模块
app.use(bodyParser.json());


// render-对网页模板进行渲染,render的参数就是模板的文件名,默认放在子目录views中
app.get('/',function(req,res){
    res.render('index',{title:"最近文章", entries:blogEngine.getBlogEntries()})
})
app.get('/about',function(req,res){
    res.render('about', {title:"自我介绍"})
})
app.get('/article/:id',function(req,res){
    var entry = blogEngine.getBlogEntry(req.params.id)
    res.render('article',{title:entry.title,blog:entry})
})

app.listen(3000)



    {{title}}


    {{{body}}}
    



文章列表

{{#each entries}}

{{title}}
Published:{{published}}

{{/each}}

自我介绍

正文


{{blog.title}}

Published: {{blog.published}}

{{blog.body}}

node app.js
image.png

你可能感兴趣的:(Express - 动态网页模板(四))