summaryrefslogtreecommitdiffstats
path: root/lib/parse/include.js
diff options
context:
space:
mode:
authorAaron O'Mullan <aaron.omullan@gmail.com>2014-10-15 21:29:23 +0200
committerAaron O'Mullan <aaron.omullan@gmail.com>2014-10-15 21:29:23 +0200
commitce50b893e926fed8905419efc8bce4a64ab2d5dc (patch)
tree83cf19e47f26fd77072ac63aeaf2152a4b30ffa6 /lib/parse/include.js
parent49e3bbc3d6e9e128df721494e9a10eaf15b7ddc8 (diff)
parent225ff27dd15b904d6a4a784c219522a28f316a5b (diff)
downloadgitbook-ce50b893e926fed8905419efc8bce4a64ab2d5dc.zip
gitbook-ce50b893e926fed8905419efc8bce4a64ab2d5dc.tar.gz
gitbook-ce50b893e926fed8905419efc8bce4a64ab2d5dc.tar.bz2
Merge pull request #482 from GitbookIO/feature/includes
Add include support, with variables and the whole shebang
Diffstat (limited to 'lib/parse/include.js')
-rw-r--r--lib/parse/include.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/lib/parse/include.js b/lib/parse/include.js
new file mode 100644
index 0000000..5fba2be
--- /dev/null
+++ b/lib/parse/include.js
@@ -0,0 +1,48 @@
+var _ = require('lodash');
+var fs = require('graceful-fs');
+var path = require('path');
+
+
+// Include helper
+function importInclude(name, paths) {
+ return paths
+ .map(function(folder) {
+ // Try including snippet from FS
+ try {
+ var fname = path.join(folder, name);
+ // Trim trailing newlines/space of imported snippets
+ return fs.readFileSync(fname, 'utf8').trimRight();
+ } catch(err) {}
+ })
+ .filter(Boolean)[0];
+}
+
+function includer(ctx, folders) {
+ return function(key) {
+ key = key.trim();
+ return ctx[key] || importInclude(key, folders);
+ };
+}
+
+module.exports = function(markdown, folder, ctx) {
+ // List of folders to search for includes
+ var folders = [];
+
+ // Handle folder arg (string or array)
+ if(_.isString(folder)) {
+ folders = [folder];
+ } else if(_.isArray(folder)) {
+ folders = folder;
+ }
+
+ // variable context
+ ctx = ctx || {};
+
+ // Memoized include function (to cache lookups)
+ var _include = _.memoize(includer(ctx, folders));
+
+ return markdown.replace(/{{([\s\S]+?)}}/g, function(match, key) {
+ // If fails leave content as is
+ return _include(key) || match;
+ });
+};