前端速学成财:第十二课-实战演练:用gulp像CMS那样生成新闻页面

上节课 我们通过gulp-template 写入静态数据生成了一个HTML文件;
那么这节课 我们继续实战提高一下。

NodeJS Request模块
npm instal request --save-dev
有了这个库,我们可以在NodeJS里面方便的实现类似curl功能.
npm install gulp-rename --save-dev

news.php

<?php
    $news=new stdClass();
    $news->id=123;
    $news->title="标题";
    $news->content="内容";
    exit(json_encode($news));

将我们前几节课的node_modules/sxin/slib.js 改造下

var req=require("request");

exports.loadNews=function(doSomething){
    req.get("http://localhost:1024/news.php",function (err,response,body) {
        if (!err && response.statusCode==200)
        {
            doSomething(body);
        }
    });
}

gulpfile.js


var gulp_tpl = require('gulp-template');
var gulp_rename=require('gulp-rename');

gp.task("news", function () {
    var getNews=require("sxin");

    getNews.loadNews(function(body)
    {
        var news=JSON.parse(body);
        gp.src(['index.html'])
            .pipe(gulp_tpl(news))
            .pipe(gulp_rename(news.id+".html"))
            .pipe(gp.dest('./build/html'));
    });
});

index.html 模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>标题:<%=title %></h1>
<h2>内容:<%=content %></h2>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值