Search code examples
javascriptjsongulpgulp-watchgulp-cheerio

How I replace values in HTML attributes via config.json file with Gulp?


Let's say I have a JSON file with the pairs:

{
  "Table":{
    "fullwidth": "680",
    "color": "#33d025",
    "margin1": "30",
    "margin2": "60",
    "padding": "20"
  }
}

then, I want to read those values and use them to replace attributes in an html file that looks like this:

<table width="{{Table.fullwidth}}" bgcolor="{{Table.color}}" style="margin: {{Table.margin1}}px {{Table.margin2}}px;">
  <tr>
    <td style="padding: {{Table.padding}}px;">
      <img src="a.jpg">
    </td>
  </tr>
</table>

So, with the html file in a "temp/" path, after gulping, I obtain a valid html file in "dist/" with the attributes changed looking like this:

<table width="680" bgcolor="#33d025" style="margin: 30px 60px;">
  <tr>
    <td style="padding: 20px;">
      <img src="a.jpg">
    </td>
  </tr>
</table>

I have already tried gulp-token-replace but after running it once, it won't work again if I save new values in the json file, even when it triggers the watch function, forcing me to restart the "gulp".

Is there a gulp plugin that can do this? or a technique that can replace the gulp-token-replace?

Maybe just javascript, but, can I run something like that from inside a gulp process (running watch to refresh it)?

Gulpfile.js as requested:

// Include gulp
var gulp = require('gulp'),

// Include plugins
fileinclude = require('gulp-file-include'),
rename = require('gulp-rename'),
images = require('gulp-imagemin'),
cache = require('gulp-cache'),
browserSync = require('browser-sync').create(),
reload = browserSync.reload,
runSequence = require('run-sequence'),
del = require('del'),
notify = require('gulp-notify'),
gtr = require('gulp-token-replace')

// Default Task
gulp.task('default', function (cb) {
runSequence('clean', ['AA', 'BB', 'CC', 'watch'], cb);
});

// TASKS

// Clean 'dist'
gulp.task('clean', function () {
return del(['HTMLTemplates/*.html', 'HTMLTemplates/img', 'Temp/*.html']);
});

// Compress images
gulp.task('BB', function () {
gulp.src('templates/img/*.{gif,jpg,png}')
    .pipe(cache(images({
        optimizationLevel: 4,
        progressive: true,
        interlaced: true
    })))
    .pipe(gulp.dest('Templates/img/'));
});

// Reload browser
gulp.task('reload', function () {
browserSync.reload();
});

// Prepare Browser-sync
gulp.task('CC', ['AA'], function () {
browserSync.init({
    // browserSync.init(['templates/*/*.html'], {
    //proxy: 'your_dev_site.url'
    server: {
        baseDir: './HTMLTemplates'
    }
});
});

// MAIN TASKS

gulp.task('AA', function (cbk) {
runSequence('fileinclude', 'trp', cbk);
});

// Force to run fileinclude first before replacing the tokens
gulp.task('trp', ['fileinclude'], function (done) {
function onFinish(event) {
    if (event.task === 'tokenreplace') {
        gulp.removeListener('task_stop', onFinish);
        done();
    }
}
gulp.on('task_stop', onFinish);
gulp.start('tokenreplace');
});

// Include partial files into email template (fileinclude)
gulp.task('fileinclude', function () {
// grab 'template'
return gulp.src('templates/layouts/*.tpl.html')
    // include partials
    .pipe(fileinclude({
        basepath: 'templates/components/'
    }))
    // remove .tpl.html extension name
    .pipe(rename({
        extname: ""
    }))
    // add new extension name
    .pipe(rename({
        extname: ".html"
    }))
    // move file to folder
    .pipe(gulp.dest('Temp/'))
    .pipe(notify({
        message: 'Template file includes complete'
    }));
});

// Replace tokens in the index.html created by fileinclude
gulp.task('tokenreplace', ['fileinclude'], function (doit) {
var config = require('./templates/components/000 vars/config.json');
return gulp.src('Temp/index.html')
    .pipe(gtr({
        global: config
    }))
    .pipe(gulp.dest('HTMLTemplates/'))
    // notify to say the task has complete
    .pipe(browserSync.stream())
    .pipe(notify({
        message: 'Vars includes complete'
    })), doit();
});

// END of MAIN TASKS

// WATCH

// Watch files for changes in html/css/tpl.html/images
gulp.task('watch', function () {
gulp.watch(['templates/components/**/*.html'], ['AA']);
gulp.watch(['templates/components/**/*.css'], ['AA']);
gulp.watch(['templates/layouts/*.tpl.html'], ['AA']);
gulp.watch(['templates/components/000 vars/*.json'], ['trp']);
gulp.watch(['HTMLTemplates/*.html'], ['reload']);
gulp.watch('templates/img/*', ['BB']);
});

Solution

  • I received the answer directly from the developer of the Gulp Token Replace plugin, so I'm answering my own question for archive purposes.

    Replace this:

    // Replace tokens in the index.html created by fileinclude
    gulp.task('tokenreplace', ['fileinclude'], function (doit) {
      var config = require('./templates/components/000 vars/config.json');
      return gulp.src('Temp/index.html')
      .pipe(gtr({
      global: config
    }))
    

    with this:

    // Replace tokens in the index.html created by fileinclude
    gulp.task('tokenreplace', ['fileinclude'], function (doit) {
      delete require.cache[require.resolve('./templates/components/000 vars/config.json')]
      var config = require('./templates/components/000 vars/config.json');
      return gulp.src('Temp/index.html')
      .pipe(gtr({
      global: config
    }))
    

    And now it works like a charm!