diff --git a/README.md b/README.md index 9f5f841..0abac50 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,9 @@ gulp.task('views', function buildHTML() { - `opts.client` (`Boolean`): Compile Pug to JavaScript code. - `opts.pug`: A custom instance of Pug for `gulp-pug` to use. - `opts.verbose`: display name of file from stream that is being compiled. - + - `opts.namespace`: sets a namespace that's used for accessing the templates on client + - `opts.processname`: a function that takes the filename for the template and creates a unique function name to access the template when compiling to the client (the template function will be on the namespace defined with `opts.namespace`) + To change `opts.filename` use [`gulp-rename`][gulp-rename] before `gulp-pug`. Returns a stream that compiles Vinyl files as Pug. diff --git a/index.js b/index.js index 8fbd5cd..7276b22 100644 --- a/index.js +++ b/index.js @@ -7,12 +7,45 @@ var ext = require('gulp-util').replaceExtension; var PluginError = require('gulp-util').PluginError; var log = require('gulp-util').log; +// A function to make the namespace client templates are compiled to +function getNamespaceDeclaration(ns) { + var output = []; + var curPath = 'this'; + + if (ns !== 'this') { + var nsParts = ns.split('.'); + nsParts.forEach(function(curPart) { + if (curPart !== 'this') { + curPath += '[' + JSON.stringify(curPart) + ']'; + output.push(curPath + ' = ' + curPath + ' || {};'); + } + }); + } + + return { + namespace: curPath, + declaration: output.join('\n') + }; +} + module.exports = function gulpPug(options) { var opts = objectAssign({}, options); var pug = opts.pug || opts.jade || defaultPug; opts.data = objectAssign(opts.data || {}, opts.locals || {}); + // filename conversion for templates + var defaultProcessName = function(name) { + return name.replace('.pug', ''); + }; + + var processName = opts.processName || defaultProcessName; + + var nsInfo; + if (opts.namespace) { + nsInfo = getNamespaceDeclaration(opts.namespace); + } + return through.obj(function compilePug(file, enc, cb) { var data = objectAssign({}, opts.data, file.data || {}); @@ -27,11 +60,20 @@ module.exports = function gulpPug(options) { try { var compiled; var contents = String(file.contents); + + var localFilePath = file.path.replace(process.cwd() + '/', ''); + var filename = processName(localFilePath); + if (opts.verbose === true) { log('compiling file', file.path); } if (opts.client) { compiled = pug.compileClient(contents, opts); + + if (opts.namespace) { + compiled = nsInfo.namespace + '[' + JSON.stringify(filename) + + '] = ' + compiled; + } } else { compiled = pug.compile(contents, opts)(data); }