Skip to content

Commit

Permalink
Pass file.contents as Twig data option
Browse files Browse the repository at this point in the history
Allows modification of template contents in Gulp stream, avoids file system access. Fixes simon-dt#30.
  • Loading branch information
mgburns committed Nov 9, 2016
1 parent eca1681 commit db93f41
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = function (options) {
twig = Twig.twig,
twigOpts = {
path: file.path,
data: String(file.contents),
async: false
},
template;
Expand Down
30 changes: 30 additions & 0 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ var fs = require('fs');
var path = require('path');
var should = require('should');
var gutil = require('gulp-util');
var fm = require('front-matter');
var twig = require('../');

require('mocha');
Expand Down Expand Up @@ -95,4 +96,33 @@ describe('gulp-twig', function () {
twg.write(fakeFile);
});

it('should use file contents as template', function(done) {
var twg = twig();

var fakeFile = new gutil.File({
base: 'test/',
cwd: 'test/',
path: path.join(__dirname, '/templates/file.twig'),
contents: fs.readFileSync(__dirname + '/templates/file-with-fm-header.twig'),
});

// simulate data attribute being added by gulp-data plugin
fakeFile['data'] = {
title: 'twig'
};

// simulate removal of front matter header
var body = fm(String(fakeFile.contents)).body;
fakeFile.contents = Buffer(body);

twg.on('data', function (newFile) {
should.exist(newFile);
should.exist(newFile.contents);
should.exist(newFile.path);
String(newFile.contents).should.equal(fs.readFileSync(__dirname + '/expected/file.html', 'utf8'));
done();
});
twg.write(fakeFile);
});

});
19 changes: 19 additions & 0 deletions test/templates/file-with-fm-header.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
foo: bar
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test {{ title|default('no options') }}</title>
</head>
<body>

<footer>
<p>
Source file: {{ _file.relative }}<br>
Target file: {{ _target.relative }}
</p>
</footer>
</body>
</html>

0 comments on commit db93f41

Please sign in to comment.