简体   繁体   English

Gulp:根据文件名替换HTML文件中的变量

[英]Gulp: replace variables in HTML file based on file name

Our project is using Gulp. 我们的项目正在使用Gulp。 Now I have a requirement: we have multiple page-level HTML files, say login.html and my.html . 现在我有一个要求:我们有多个页面级HTML文件,例如login.htmlmy.html Inside these original HTML files there is a variable called {{PAGE_TITLE}} , which should be replaced (by Gulp ) to be "Login to System" and "My Account" respectively. 在这些原始HTML文件中,有一个名为{{PAGE_TITLE}}的变量,应将其替换(由Gulp替换)分别为"Login to System""My Account" Here is my current script: 这是我当前的脚本:

gulp.task('pages', ['clean:tmp'], function () {
    var pageTitle = '';
    return gulp.src('/my/source/html/**/*.html')
        .pipe(tap(function (file, t) {
            pageTitle = /index.html$/.test(file.path) ? 'Login to System' : 'My Account';
        }))
        .pipe(replace(/{{PAGE_TITLE}}/g, pageTitle))
        .pipe(gulp.dest('/my/dest/'));
});

It turns out the variable pageTitle is never set before the replace . 原来,可变pageTitle之前从未设置replace I have searched for documentation of gulp-tap for tons of times, but I still do not know how to make it work. 我已经搜索了很多次有关gulp-tap文档,但是我仍然不知道如何使其工作。 Please help, thanks. 请帮忙,谢谢。

This post: Modify file in place (same dest) using Gulp.js and a globbing pattern tries to achieve the same affect, but he resulted in some other solution. 这篇文章: 使用Gulp.js在本地修改文件(相同的目标),并且通配模式试图实现相同的效果,但是他提出了其他解决方案。

I figured out the solution as followed: 我想出了如下解决方案:

gulp.task('pages', ['clean:tmp'], function () {

    function replaceDynamicVariables(file) {
        var pageTitle = /login.html$/.test(file.path) ? 'Login to System' : 'My Account';
        file.contents = new Buffer(String(file.contents)
            .replace(/{{PAGE_TITLE}}/, pageTitle)
        );
    }

    return gulp.src('/my/source/html/**/*.html')
        .pipe(tap(replaceDynamicVariables))
        .pipe(gulp.dest('/my/dest/'));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM