How to get output html in different language using gulp-data?

1.9k views Asked by At

This is my gulp file

var gulp = require('gulp');
var posthtml = require('gulp-posthtml');
var mjml = require('gulp-mjml');
var nunjucksRender = require('gulp-nunjucks-render');
var data = require('gulp-data');



gulp.task('html', function() {
  var plugins = [
      require('posthtml-lorem')(),
       ];
  // Gets .html and .nunjucks files in pages
  return gulp.src('./pages/**/*.+(html|nunjucks)')
  // Adding data to Nunjucks
  .pipe(data(function() {
    return require('./data.json')
  }))
  // Renders template with nunjucks
  .pipe(nunjucksRender({
      path: ['./helpers/']
    }))
  .pipe(posthtml(plugins))
  .pipe(mjml())
  // output files in app folder
  .pipe(gulp.dest('./dest'))
});

This could be json file for data data.json

{
  "Page title": "hello English"
 }

I want to have two files in ./dest folder home.html and home_de.html And home.html should have content in English and home_de.html should have content in german. I don't want to have different source HTML template file for a different language.

Content to data file (.json) will be added manually

1

There are 1 answers

4
Popcorn245 On BEST ANSWER

Gulp is just a simple wrapper around node.js. By requiring fs you can access the file system. Then you can loop through the different language data files and render the html for each one. This should do the trick, however this is untested, but you should get the gist.

var fs = require('fs');
var gulp = require('gulp');
var posthtml = require('gulp-posthtml');
var mjml = require('gulp-mjml');
var nunjucksRender = require('gulp-nunjucks-render');
var data = require('gulp-data');



gulp.task('html', function() {
    var plugins = [
       require('posthtml-lorem')(),
    ];

    fs.readdir('./languages/',function(err,files){
        if(err) throw err;
            files.forEach(function(file){
                var language = file.split('.')[0];
                // Gets .html and .nunjucks files in pages
                return gulp.src('./pages/**/*.+(html|nunjucks)')
                // Adding data to Nunjucks
                .pipe(data(function() {
                    return require('./languages/' + language + '.json')
                }))
                // Renders template with nunjucks
                .pipe(nunjucksRender({
                    path: ['./helpers/']
                }))
                .pipe(posthtml(plugins))
                .pipe(mjml())
                // output files in app folder
                .pipe(gulp.dest('./dest/' + language));
        });
    });
});