Created
July 17, 2014 21:53
-
-
Save tylersticka/146449c83df832a18b53 to your computer and use it in GitHub Desktop.
Simple Knockout template inclusion with Gulp
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
// include gulp + template plugin | |
var gulp = require('gulp'); | |
var template = require('gulp-template'); | |
// include the koTemplates module locally | |
var koTemplates = require('./koTemplates'); | |
// create the 'templates' task | |
gulp.task('templates', function () { | |
// single-page app, so just pipe through index | |
gulp.src('./src/templates/index.html') | |
// pipe to template plugin with koTemplates as an array | |
// containing all of the individual template files | |
.pipe(template({ | |
koTemplates: koTemplates('./src/templates/ko') | |
})) | |
// output the result to the build directory | |
.pipe(gulp.dest('./build')); | |
}); |
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
<!doctype html> | |
<html> | |
<body> | |
<p>This content is just plain content in the HTML.</p> | |
<!-- But here, we loop through the koTemplates array and output it to script tags: --> | |
<% koTemplates.forEach(function (template) { %> | |
<script type="text/html" id="<%= template.name %>-template"> | |
<%= template.content %> | |
</script> | |
<% }) %> | |
<!-- include your dependencies, bundled scripts, etc. afterward --> | |
</body> | |
</html> |
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 fs = require('fs'); | |
var path = require('path'); | |
// accepts a directory and optional file extension | |
// (defaults to html), pushes all of them to an array | |
// as objects with a 'name' and 'content' attribute | |
module.exports = function (dir, ext) { | |
var templates = []; | |
var files = fs.readdirSync(dir); | |
ext = ext || 'html'; | |
files.forEach(function (file, index) { | |
templates.push({ | |
name: path.basename(file, '.' + ext), | |
content: fs.readFileSync(dir + '/' + file, 'utf8') | |
}); | |
}); | |
return templates; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment