UNPKG

2.06 kBJavaScriptView Raw
1
2var consolidate = require('consolidate');
3var debug = require('debug')('metalsmith-layouts');
4var each = require('async').each;
5var extend = require('extend');
6var match = require('multimatch');
7var omit = require('lodash.omit');
8
9/**
10 * Expose `plugin`.
11 */
12
13module.exports = plugin;
14
15/**
16 * Settings.
17 */
18
19var settings = ['engine', 'directory', 'pattern', 'default'];
20
21/**
22 * Metalsmith plugin to run files through any layout in a layout `dir`.
23 *
24 * @param {String or Object} options
25 * @property {String} default (optional)
26 * @property {String} directory (optional)
27 * @property {String} engine
28 * @property {String} pattern (optional)
29 * @return {Function}
30 */
31
32function plugin(opts){
33 opts = opts || {};
34 if ('string' == typeof opts) opts = { engine: opts };
35 if (!opts.engine) throw new Error('"engine" option required');
36
37 var engine = opts.engine;
38 var dir = opts.directory || 'layouts';
39 var pattern = opts.pattern;
40 var def = opts.default;
41 var params = omit(opts, settings);
42
43 return function(files, metalsmith, done){
44 var metadata = metalsmith.metadata();
45
46 function check(file){
47 var data = files[file];
48 var lyt = data.layout || def;
49 if (pattern && !match(file, pattern)[0]) return false;
50 if (!lyt) return false;
51 return true;
52 }
53
54 Object.keys(files).forEach(function(file){
55 if (!check(file)) return;
56 debug('stringifying file: %s', file);
57 var data = files[file];
58 data.contents = data.contents.toString();
59 });
60
61 each(Object.keys(files), convert, done);
62
63 function convert(file, done){
64 if (!check(file)) return done();
65 debug('converting file: %s', file);
66 var data = files[file];
67 var clone = extend({}, params, metadata, data);
68 var str = metalsmith.path(dir, data.layout || def);
69 var render = consolidate[engine];
70
71 render(str, clone, function(err, str){
72 if (err) return done(err);
73 data.contents = new Buffer(str);
74 debug('converted file: %s', file);
75 done();
76 });
77 }
78 };
79}