Created
March 15, 2015 09:40
-
-
Save robozevel/d1201d02fa9f8a7702b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var fs = require('fs'); | |
var cheerio = require('cheerio'); | |
var createTemplate = function(id, markup) { | |
var $ = cheerio.load('<script type="text/ng-template"></script>'); | |
$('script').attr('id', id).html(markup).html(); | |
return $.html(); | |
}; | |
var preload = function(filePath, options) { | |
if (!fs.existsSync(filePath)) throw new Error(filePath + ' doesn\'t exist'); | |
var content = fs.readFileSync(filePath); | |
var $ = cheerio.load(content); | |
options = Object(options); | |
$('[ng-include]').each(function(i, el) { | |
var templateUrl = el.attribs['ng-include'].replace(/^'|'$/g, ''); | |
var templatePath = path.resolve('client', templateUrl); | |
if (fs.existsSync(templatePath)) { | |
if (options.cacheTemplates) { | |
// Appends <script> tags to populate $templateCache (https://docs.angularjs.org/api/ng/service/$templateCache) | |
$('head').append(createTemplate(templateUrl, fs.readFileSync(templatePath))); | |
} else { | |
// Injects the template's content into the element | |
$(el).removeAttr('ng-include').html(fs.readFileSync(templatePath)); | |
} | |
} | |
}); | |
var markup = $.html(); | |
return function(req, res, next) { | |
res.send(markup); | |
}; | |
}; | |
module.exports = { | |
preload: preload | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment