ejs-使用Gulp生成靜態頁面


gulpfile.js里添加var ejs require('gulp-ejs')

命令行中執行: npm install gulp-ejs

gulp.task('gulp-ejs', function(){

  gulp.src(模版目錄 + '/**/*.html')
  .pipe(data(function (file) {
  var filePath = file.path;
    // global.json 全局數據,頁面中直接通過屬性名調用
    return Object.assign(JSON.parse(fs.readFileSync(模版目錄+ '/global.json')), {
      // local: 每個頁面對應的數據,頁面中通過 local.屬性 調用
      local: JSON.parse(fs.readFileSync( path.join(path.dirname(filePath), path.basename(filePath, '.html') + '.json')))
    })
  }))
  .pipe(ejs().on('error', function(err) {
    gutil.log(err);
    this.emit('end');
  }))
  .pipe(gulp.dest(生成目錄));
});

目錄結構

 

1._golobal文件下的head.ejs

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><%= local.title %></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<link rel="shortcut icon" href="網站圖標路徑"/>
<% styles.forEach(function(sty){ %>

<link rel="stylesheet" href="<%= sty %>">

<% }) %>

上面引用公用css下面引用單獨頁面css樣式

<%
if(local.styles) {
local.styles.forEach(function(sty){ %>

<link rel="stylesheet" href="<%= sty %>">

<% })

}
%>
</head>

2._golobal文件下的foot.ejs

<% scripts.forEach(function(js){ %>

<script src="<%= js %>"></script>

<% }) %>

上面引用公用js下面引用單獨頁面js樣式
<%
if(local.scripts) {
local.scripts.forEach(function(js){ %>

<script src="<%= js %>"></script>

<% })
}
%>

3.global.json公用js跟css

{
  "_ImgUrl":"頁面公用圖片路徑",
  "styles": [
    "/PubCss/base.min.css"
  ],
  "scripts": [
    "/framework/common/jquery-1.9.1.min.js"
  ]
}

4.goodsList文件下goodsList.html

<%- include('../../_global/head') %>  (引用css)

<body>

<%- include('../../_partial/header') %>(引用公共頭部)

<%- include('../../_partial/goodsList') %>(引用單獨頁面內容)

<%- include('../../_partial/footer') %>(引用公共頁尾)

<%- include('../../_global/foot') %>(引用js)

</body>
</html>

4.goodsList文件下goodsList.json

{
  "title": "個人中心",
  "styles": [
    "個人中心css樣式"
  ],
  "scripts": [
    "個人中心js樣式"
  ]
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM