Skip to content

Instantly share code, notes, and snippets.

@tylersticka
Created July 17, 2014 21:53
Show Gist options
  • Save tylersticka/146449c83df832a18b53 to your computer and use it in GitHub Desktop.
Save tylersticka/146449c83df832a18b53 to your computer and use it in GitHub Desktop.
Simple Knockout template inclusion with Gulp
// 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'));
});
<!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>
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