diff options
author | Samy Pessé <samypesse@gmail.com> | 2016-03-15 12:37:52 +0100 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2016-03-15 12:37:52 +0100 |
commit | 0b4db49f5752fd2a6f72c3ba57cdb5c1b5b8ae4e (patch) | |
tree | 2b2dede4d212d40992a829cd33151d35a7a7d91d /lib/template/fs-loader.js | |
parent | c499a8a13a3059e3953727866beb7c986e46dd78 (diff) | |
parent | fbffd54aa244d8a969200b0efbed3d7dc9eb73d0 (diff) | |
download | gitbook-0b4db49f5752fd2a6f72c3ba57cdb5c1b5b8ae4e.zip gitbook-0b4db49f5752fd2a6f72c3ba57cdb5c1b5b8ae4e.tar.gz gitbook-0b4db49f5752fd2a6f72c3ba57cdb5c1b5b8ae4e.tar.bz2 |
Merge pull request #1181 from GitbookIO/feature/allplugins_tpl
All plugins can extend templates/theme
Diffstat (limited to 'lib/template/fs-loader.js')
-rw-r--r-- | lib/template/fs-loader.js | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/template/fs-loader.js b/lib/template/fs-loader.js new file mode 100644 index 0000000..00c4743 --- /dev/null +++ b/lib/template/fs-loader.js @@ -0,0 +1,61 @@ +var _ = require('lodash'); +var fs = require('fs'); +var path = require('path'); +var nunjucks = require('nunjucks'); + +/* + Nunjucks loader similar to FileSystemLoader, but avoid infinite looping +*/ + +function isRelative(filename) { + return (filename.indexOf('./') === 0 || filename.indexOf('../') === 0); +} + +var Loader = nunjucks.Loader.extend({ + init: function(searchPaths) { + this.searchPaths = searchPaths.map(path.normalize); + }, + + getSource: function(fullpath) { + if (!fullpath) return null; + + fullpath = this.resolve(null, fullpath); + + if(!fullpath) { + return null; + } + + return { + src: fs.readFileSync(fullpath, 'utf-8'), + path: fullpath, + noCache: true + }; + }, + + // We handle absolute paths ourselves in ".resolve" + isRelative: function() { + return true; + }, + + resolve: function(from, to) { + // Relative template like "./test.html" + if (isRelative(to) && from) { + return path.resolve(path.dirname(from), to); + } + + // Absolute template to resolve in root folder + var resultFolder = _.find(this.searchPaths, function(basePath) { + var p = path.resolve(basePath, to); + + return ( + p.indexOf(basePath) === 0 + && p != from + && fs.existsSync(p) + ); + }); + if (!resultFolder) return null; + return path.resolve(resultFolder, to); + } +}); + +module.exports = Loader; |