html - 使用 grunt js,如何将 <title> 动态添加到静态 html 文件?

标签 html json build-process concatenation gruntjs

更具体地说,我想通过引用外部 JSON 文件来添加标题,我们称它为 titles.json。

我使用 grunt 的其中一件事是构建用于设计和调试的静态 HTML 文件。这在开发过程中非常有用,不仅对标题而且对其他潜在数据也是如此,例如设置事件导航链接。

我目前正在使用此处接受的答案所描述的过程连接 HTML 文件: Using grunt concat, how would I automate the concatenation of the same file to many other files?

编辑:我现在使用 assemble为此,创建它是为了使使用模板和外部数据变得非常容易。

最佳答案

这是我的看法。使用 grunt 的标准模板机制,页面元数据在实际页面文件之外的对象中定义,正如您所建议的(我不能说我喜欢这样)。

gruntfile(包括来自 Using grunt concat, how would I automate the concatenation of the same file to many other files?wrap 任务):

/*global module:false*/    
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    meta: {
      version: '0.1.0',
      banner: '/*! PROJECT_NAME - v<%= meta.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '* http://PROJECT_WEBSITE/\n' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
        'YOUR_NAME; Licensed MIT */'
    },

    // Paths
    project: {
      partials: 'assets/partials',  // don't put trailing slash
      pages:    'assets/pages',     // don't put trailing slash
      less:     'assets/less',
      css:      'assets/css',
      img:      'assets/img',
      js:       'assets/js'
    },

    // Used for page title and nav generation.
    // It's an array to ensure correct order for nav
    pages: [{   
        file: 'index.html',
        title: 'My homepage'
        /* This format can be extended to something like:
         * {
         *      title: 'My homepage',
         *      header: 'Welcome to my site',
         *      navtitle: 'Home'
         * }
         * Although I think it's best to keep page metadata as close to content as possible,
         * i.e. right inside pages files (think YAML headers in Jekyll pages)  
         */
    }, {
        file: 'about.html',
        title: 'About me'
    }, {
        file: 'contact.html',
        title: 'Contact'
    }],

    // wraps files with header and footer
    wrap: {
        html: {
            header: '<%= project.partials %>/head.tmpl',
            footer: '<%= project.partials %>/footer.tmpl',
            src: [
                '<%= project.pages %>/index.html',
                '<%= project.pages %>/about.html',
                '<%= project.pages %>/contact.html'
            ],
            dest: '.'   // destination *directory*, probably better than specifying same file names twice
        }
    },

    // processes templates in page files
    buildPages: {
        pages: '<config:pages>',    // page files metadata
        dir: '.'                    // page files location dir
    }

  });


  // Default task.
  grunt.registerTask('default', 'wrap buildPages');

  grunt.registerMultiTask('wrap', 'Wraps source files with specified header and footer', function() {
        var data = this.data,
            path = require('path'),
            dest = grunt.template.process(data.dest),
            files = grunt.file.expandFiles(this.file.src),
            header = grunt.file.read(grunt.template.process(data.header)),
            footer = grunt.file.read(grunt.template.process(data.footer)),
            sep = grunt.utils.linefeed; 

        files.forEach(function(f) {
            var p = dest + '/' + path.basename(f),
                contents = grunt.file.read(f);

            grunt.file.write(p, header + sep + contents + sep + footer);
            grunt.log.writeln('File "' + p + '" created.');
        });
  });

  grunt.registerTask('buildPages', 'Processes templates in page files', function() {
  // NOTE: current implementation replaces files
    var data = grunt.config('buildPages'),
        pages = data.pages,
        dir = data.dir,
        contents,
        curPath;

    pages.forEach(function(page) {
        curPath = dir + '/' + page.file;
        contents = grunt.file.read(curPath);

        // feed the entire pages array and current entry to the template
        grunt.file.write(curPath, grunt.template.process(contents, {
            pages: pages,
            curPage: page
        }));
        grunt.log.writeln('Page at "' + curPath + '" built.');
    });
  });
};

head.tmpl:

<!DOCTYPE html>
<html>
    <head>
        <title><%= curPage.title %></title>
    </head>
    <body>
        <!-- NAV -->
        <ul class="nav">
            <%
                pages.forEach(function(p) {
                    print(
                        '<li class="' + ((curPage === p) ? 'active' : '') + '">' +
                            ((curPage === p) ? p.title : ('<a href="' + p.file + '">' + p.title + '</a>')) + 
                        '</li>\n'
                    );
                });
            %>
        </ul>
        <!-- /NAV -->

        <!-- MAIN CONTENT -->
        <div class="main">

页脚.tmpl:

        </div>
        <!-- /MAIN CONTENT -->
    </body>
</html>

关于html - 使用 grunt js,如何将 &lt;title&gt; 动态添加到静态 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982396/

相关文章:

build-process - Team Build的版本号和$(Rev :. r)

javascript - eclipse 刻草图 : Columns will resize, 但行不会。 (CSS 网格)

html - 在 flexbox 中使用 'height: 100%' 和 'align-items: stretch'

html - 在 CSS 中合并菱形和六边形?

java - 在 Groovy 中实现 Object-JSON 映射的标准方法是什么?

json - 使用 codeable 解析 JSON 时出错

jenkins - 如果现有构建因超时而失败,则触发另一个作业

html - 取消设置 :visited vs a:link 的背景值

jquery - 文件上传失败,但 jqXHR 在 IE8 中返回状态 200

java - 为什么是 maven ?有什么好处?