Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 4
}
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: node_js
node_js:
- 4
- 6
- 10
- 12
before_install:
- npm install -g istanbul
- npm install -g codeclimate-test-reporter
Expand Down
113 changes: 59 additions & 54 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@
</tr>
<tr>
<td>Node Version</td>
<td>>= 4</td>
<td>>= 10</td>
</tr>
<tr>
<td>Gulp Version</td>
<td>3.x</td>
</tr>
</table>


Compile [Twig.js](https://github.com/justjohn/twig.js) templates with Gulp. Build upon [Twig.js](https://github.com/justjohn/twig.js) , the JS port of the Twig templating language by John Roepke.

You can use this plugin with [gulp-data](https://www.npmjs.com/package/gulp-data).
Expand All @@ -30,6 +29,7 @@ You can use this plugin with [gulp-data](https://www.npmjs.com/package/gulp-data
```bash
npm install gulp-twig --save
```

### Example

```html
Expand All @@ -55,91 +55,97 @@ npm install gulp-twig --save
{# layout.twig #}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="description" content="A demo of how to use gulp-twig"/>
<meta name="author" content="Simon de Turck"/>
<meta name="viewport" content="width=device-width,initial-scale=1">

<title>{{ title }}</title>

</head>
<body>
<section>
{% block page %}{% endblock %}
</section>
</body>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="A demo of how to use gulp-twig" />
<meta name="author" content="Simon de Turck" />
<meta name="viewport" content="width=device-width,initial-scale=1" />

<title>{{ title }}</title>
</head>
<body>
<section>
{% block page %}{% endblock %}
</section>
</body>
</html>
```

```javascript
var gulp = require('gulp');

gulp.task('compile', function () {
gulp.task('compile', function() {
'use strict';
var twig = require('gulp-twig');
return gulp.src('./index.twig')
.pipe(twig({
data: {
title: 'Gulp and Twig',
benefits: [
'Fast',
'Flexible',
'Secure'
]
}
}))
return gulp
.src('./index.twig')
.pipe(
twig({
data: {
title: 'Gulp and Twig',
benefits: ['Fast', 'Flexible', 'Secure'],
},
}),
)
.pipe(gulp.dest('./'));
});

gulp.task('default', ['compile']);
```

### Options:
**data**: [object| *The data that is exposed in the twig files. Or use gulp-data to pipe files directly into gulp-twig*

**base**: [string] *sets the views base folder. Extends can be loaded relative to this path*
**data**: [object| _The data that is exposed in the twig files. Or use gulp-data to pipe files directly into gulp-twig_

**errorLogToConsole**: [true|false] _logs errors to console (defaults to false)_

**onError**: [function] _handle error yourself_

**cache**: [true|false] _enables the Twig cache. (defaults to false)_

**errorLogToConsole**: [true|false] *logs errors to console (defaults to false)*
**extend**: [function (Twig)] _extends Twig with new tags types. The Twig attribute is Twig.js's internal object. [Read more here](https://github.com/justjohn/twig.js/wiki/Extending-twig.js-With-Custom-Tags)_

**onError**: [function] *handle error yourself*
**extname**: [string|true|false] _output file extension including the '.' like path.extname(filename). Use `true` to keep source extname and a "falsy" value to drop the file extension_

**cache**: [true|false] *enables the Twig cache. (defaults to false)*
**useFileContents**: [true|false] _use file contents instead of file path (defaults to false) [Read more here](https://github.com/zimmen/gulp-twig/issues/30)_

**debug**: [true|false] *enables debug info logging (defaults to false)*
**twigParameters**: [object] _Parameters for creating a Twig template._

**trace**: [true|false] *enables tracing info logging (defaults to false)*
- **base**: [string] _sets the views base folder. Extends can be loaded relative to this path_

**extend**: [function (Twig)] *extends Twig with new tags types. The Twig attribute is Twig.js's internal object. [Read more here](https://github.com/justjohn/twig.js/wiki/Extending-twig.js-With-Custom-Tags)*
- **debug**: [true|false] _enables debug info logging (defaults to false)_

**extname**: [string|true|false] *output file extension including the '.' like path.extname(filename). Use `true` to keep source extname and a "falsy" value to drop the file extension*
- **trace**: [true|false] _enables tracing info logging (defaults to false)_

**useFileContents**: [true|false] *use file contents instead of file path (defaults to false) [Read more here](https://github.com/zimmen/gulp-twig/issues/30)*
- **strict_variables**: [true|false] _If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false)._

**functions**: [array] _extends Twig with given function objects. (default to undefined)_

**functions**: [array] *extends Twig with given function objects. (default to undefined)*
```javascript
[
{
name: "nameOfFunction",
func: function (args) {
return "the function";
}
}
]
name: 'nameOfFunction',
func: function(args) {
return 'the function';
},
},
];
```

**filters**: [array] *extends Twig with given filter objects. (default to undefined)*
**filters**: [array] _extends Twig with given filter objects. (default to undefined)_

```javascript
[
{
name: "nameOfFilter",
func: function (args) {
return "the filter";
}
}
]
name: 'nameOfFilter',
func: function(args) {
return 'the filter';
},
},
];
```

### LICENSE

(MIT License)
Expand All @@ -164,4 +170,3 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

143 changes: 69 additions & 74 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,109 +1,104 @@
var map = require('map-stream');
var rext = require('replace-ext');
var log = require('fancy-log');
var PluginError = require('plugin-error');
const through2 = require('through2');
const rext = require('replace-ext');
const log = require('fancy-log');
const PluginError = require('plugin-error');

const PLUGIN_NAME = 'gulp-twig';

module.exports = function (options) {
module.exports = function(options) {
'use strict';
options = Object.assign({}, {
changeExt: true,
extname: '.html',
useFileContents: false,

}, options || {});

function modifyContents(file, cb) {
var data = file.data || Object.assign({}, options.data);

function modifyContents(file, encoding, callback) {
if (file.isNull()) {
return cb(null, file);
return callback(null, file);
}

if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
}

data._file = file;
if(options.changeExt === false || options.extname === true){
data._target = {
path: file.path,
relative: file.relative
}
}else{
data._target = {
path: rext(file.path, options.extname || ''),
relative: rext(file.relative, options.extname || '')
}
return callback(new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
}

var Twig = require('twig'),
twig = Twig.twig,
twigOpts = {
path: file.path,
async: false
},
template;

if (options.debug !== undefined) {
twigOpts.debug = options.debug;
}
if (options.trace !== undefined) {
twigOpts.trace = options.trace;
}
if (options.base !== undefined) {
twigOpts.base = options.base;
}
if (options.namespaces !== undefined) {
twigOpts.namespaces = options.namespaces;
}
if (options.cache !== true) {
const {
changeExt = true,
extname = '.html',
useFileContents = false,
twigParameters = {},
data: optionsData,
cache,
functions,
filters,
extend,
errorLogToConsole,
onError,
} = options || {};

const data = file.data || optionsData || {};

const target =
changeExt === false || extname === true
? {
path: file.path,
relative: file.relative,
}
: {
path: rext(file.path, extname || ''),
relative: rext(file.relative, extname || ''),
};

const Twig = require('twig');
const { twig } = Twig;

if (cache !== true) {
Twig.cache(false);
}

if (options.functions) {
options.functions.forEach(function (func) {
if (functions) {
functions.forEach(function(func) {
Twig.extendFunction(func.name, func.func);
});
}

if (options.filters) {
options.filters.forEach(function (filter) {
if (filters) {
filters.forEach(function(filter) {
Twig.extendFilter(filter.name, filter.func);
});
}

if(options.extend) {
Twig.extend(options.extend);
delete options.extend;
}

if (options.useFileContents) {
var fileContents = file.contents.toString();
twigOpts.data = fileContents
if (extend) {
Twig.extend(extend);
}

template = twig(twigOpts);
const template = twig({
...twigParameters,
rethrow: true,
async: false,
path: file.path,
data: useFileContents ? file.contents.toString() : undefined,
});

try {
file.contents = new Buffer(template.render(data));
}catch(e){
if (options.errorLogToConsole) {
file.contents = new Buffer.from(
template.render({
...data,
_target: target,
_file: file,
}),
);
} catch (e) {
if (errorLogToConsole) {
log(PLUGIN_NAME + ' ' + e);
return cb();
return callback();
}

if (typeof options.onError === 'function') {
options.onError(e);
return cb();
if (typeof onError === 'function') {
onError(e);
return callback();
}
return cb(new PluginError(PLUGIN_NAME, e));
return callback(new PluginError(PLUGIN_NAME, e));
}

file.path = data._target.path;
cb(null, file);
file.path = target.path;
callback(null, file);
}

return map(modifyContents);
return through2.obj(modifyContents);
};
Loading