Gulp 用元值替换变量的插件

Gulp plug-in to replace variables with meta values

我正在为 Marketo 的电子邮件 2.0 应用程序构建电子邮件模板。这些模板利用变量声明。 这些被引用为元值,然后可以在基于模板生成电子邮件时对其进行编辑。变量元引用包括;字符串、布尔值、颜色、数字等

声明变量的语法如下:

<meta class="mktoNumber" id="articleSectionSpacerBottom" mktoname="Article heading spacer bottom" default="30" min="0" max="30" step="5">

在文档正文中调用变量是这样的:

${articleSpacerBottom}

我想找到一个可以处理每个变量的默认值的插件,这样我就可以在本地测试电子邮件模板。

因此,对于每个变量或变量的每个实例,找到关联的元标记并获取默认值。

我希望将其添加到 html 处理任务中,以便它在 injectsPartials 插件之后立即运行。

gulp.task('html', function () {
  gulp.src(source + '*.+(html|php)')
    .pipe($.plumber())
    .pipe($.injectPartials({
        removeTags: true
    }))
    .pipe($.inline({
        base: source,
        css: $.cleanCss,
        disabledTypes: ['svg', 'img']
    }))
    .pipe($.inlineCss({
        applyStyleTags: true,
        applyLinkTags: true,
        removeStyleTags: false,
        removeLinkTags: true,
        applyWidthAttributes: true,
        applyTableAttributes: true
    })) 
    .pipe($.replace('src="images/', 'src="' + mtkosrc + template +'-'))
    .pipe($.replace('mktoname', 'mktoName'))
    .pipe(gulp.dest(build))
    .pipe(reload({
        stream: true
    }));
});

我怀疑是否有任何开箱即用的插件可以满足您的需求。你得自己写点东西。

但这应该不会太难。您可以使用 map-stream to gain access to each vinyl file object in the stream. Then use cheerio 来解析 HTML 并找到 <meta> 标签。之后是一个简单的搜索和替换操作。

这是一个适合我的小例子:

gulpfile.js

var gulp = require('gulp');
var cheerio = require('cheerio');
var map = require('map-stream');

gulp.task('default', function() {
  gulp.src('index.html')
    .pipe(map(function(file, done) {
      var html = file.contents.toString();
      var $$ = cheerio.load(html);
      $$('meta').each(function() {
        var meta = $$(this);
        var variable = new RegExp('\$\{' + meta.attr('id') + '\}', 'g');
        html = html.replace(variable, meta.attr('default'));
      });
      file.contents = new Buffer(html);
      done(null, file);
    }))
    .pipe(gulp.dest('build'));
});

index.html

<html>
<head>
<meta class="mktoNumber" id="articleSectionSpacerBottom1" mktoname="Article heading spacer bottom" default="30" min="0" max="30" step="5">
<meta class="mktoNumber" id="articleSectionSpacerBottom2" mktoname="Article heading spacer bottom" default="42" min="0" max="30" step="5">
</head>
<body>
${articleSectionSpacerBottom1}
${articleSectionSpacerBottom2}
</body>
</html>

build/index.html

<html>
<head>
<meta class="mktoNumber" id="articleSectionSpacerBottom1" mktoname="Article heading spacer bottom" default="30" min="0" max="30" step="5">
<meta class="mktoNumber" id="articleSectionSpacerBottom2" mktoname="Article heading spacer bottom" default="42" min="0" max="30" step="5">
</head>
<body>
30
42
</body>
</html>