gruntjs -如何在HTML文件中列出文件名和这些文件名的数据属性

gruntjs - how to list filenames and data attributes of those filenames in an HTML file?

本文关键字:文件名 数据属性 文件 HTML gruntjs      更新时间:2023-09-26

我正在创建许多HTML文件,这些文件将用作开发项目的设计指南。一个HTML文件将包括以下HTML标签:

<title> Design pattern 001 </title>
<meta data-details="This design should show the basic homepage" />
<meta data-status="Approved" />

所有这些文件位于一个目录:

/designs/design-pattern-001.html    
...
/designs/design-pattern-100.html

我想运行一个grunt任务,它将使用以下语法创建一个单独的index.html:

<table>
  <tr>
    <td> Aprooved</td>
    <td> Design pattern 001 </td>
    <td> This design should show the basic homepage </td>
  </tr>
       ....
</table>

我的开发团队将使用index.html

我在这里尝试了解决方案:我如何在html中生成文件列表,使用grunt任务?但这只能得到文件名,而不能得到每个HTML中的任何数据属性。

是唯一的其他解决方案,使用jQuery(或JavaScript)来获得这为每个各自的文件像这里的解决方案:获得JavaScript本地HTML文件的HTML代码?

这可以通过grunt自定义任务来完成。我已经在github上使用您上面概述的要求构建了一个示例项目。

我能够使用以下节点模块做到这一点:

  • xmldom和xpath解析html文件
  • pug从模板创建生成的html

请查看github项目,但这里是大多数重要的代码:

繁重文件 (根项目):

定义自定义任务选项

module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        parseAndIndexHtmlFiles : {
            options : {
                output: "index.html",
                directoryToParse: "design",
                jadeTemplate: "index.jade",
                parseHtmlTags: ["title"],
                parseAttributes: ["data-details", "data-status"]
            }
        }
    });
    grunt.loadTasks('tasks');
    grunt.registerTask('default', [ "parseAndIndexHtmlFiles" ]);
};

自定义任务文件 (在项目的任务文件夹)/tasks/parseDesignHtml.js:

var DOMParser = require('xmldom').DOMParser;
var xpath = require('xpath');
var Promise = require("bluebird");
var pug = require('pug');
var tidy = require('htmltidy').tidy;
var fs = Promise.promisifyAll(require("fs"));
var options, done, globalGrunt = null;
var fileIndex = [];
module.exports = function(grunt) {
    globalGrunt = grunt;
    grunt.registerTask('parseAndIndexHtmlFiles', function () {
        done = this.async();
        options = this.options({
            output : "",
            directoryToParse : "",
            jadeTemplate : "",
            parseHtmlTags : [ ],
            parseAttributes : [ ]
        });
        parseHtmlFiles(options.directoryToParse);
    });
};
function parseHtmlFiles(directory) {

    fs.readdirAsync(directory).map(function (filename) {
        if (filename.match(/.html$/)) {
            return readFile(directory + "/" + filename);
        }
    }).then(function (results) {
        var contents = [];
        for(var i = 0; i < results.length; i++){
            if(results[i]){
                contents.push(results[i]);
            }
        }
        var html = pug.renderFile(options.jadeTemplate , {
            files : contents
        });
        tidy(html, {
            indent: true
        }, function (err, result) {
            if (err) {
                globalGrunt.fail.fatal(err);
            }
            fs.writeFile(options.output, result, function (err) {
                if (err) {
                    globalGrunt.fail.fatal(err);
                }
                done();
            });
        });
    });
}
function readFile(filename) {
    var promise = Promise.pending();
    fs.readFile(filename, function (err, data) {
        if (err) {
            promise.reject(err);
        } else if (data) {
            var doc = new DOMParser().parseFromString(data.toString(), "text/html");
            var params = parseDocument(doc);
            promise.resolve(new IndexedFile(filename, params));
        } else {
            promise.reject("No Data");
        }
    });
    return promise.promise;
}
function parseDocument(doc) {
    var params = {
        tags : {},
        attributes : {}
    };
    options.parseHtmlTags.forEach(function (tag) {
        var tags = doc.getElementsByTagName(tag);
        if (tags.length > 0) {
            params.tags[tag] = tags[0].firstChild.data;
        }
    });
    options.parseAttributes.forEach(function (attrName) {
        var attr = xpath.select("//@" + attrName, doc);
        if (attr.length > 0) {
            params.attributes[attrName] = attr[0].nodeValue;
        }
    });
    return params;
} 

function IndexedFile(path, parameters) {
    this.path = path;
    this.parameters = parameters;
}

模板文件 (项目根目录)/index.jade:

doctype html
html(lang="en")
  head
    title="Stackoverflow Question 40011711"
  body
    table
      - files.forEach(function (item) {
        tr
          td
            a(href=item.path)=item.parameters.tags["title"]
          td=item.parameters.attributes["data-status"]
          td=item.parameters.attributes["data-details"]
      - })