Skip to content

Instantly share code, notes, and snippets.

@tylersticka
Last active August 29, 2015 13:57
Show Gist options
  • Save tylersticka/9422959 to your computer and use it in GitHub Desktop.
Save tylersticka/9422959 to your computer and use it in GitHub Desktop.
Example of bespoke Gulp task that includes Knockout templates
/**
* This project's actual gulpfile contains much more than this,
* but these are the relevant bits.
*/
// Node libraries
var fs = require('fs');
var path = require('path');
// Gulp + plugins
var gulp = require('gulp');
var rename = require('gulp-rename');
var replace = require('gulp-replace');
// I store some of the paths here just to
// avoid unnecessary verboseness later on.
var paths = {
html: {
// This path could be used for a 'watch' task later
src: 'src/**/*.html',
// Main file to read
main: 'src/index.html',
// Template folder
templates: 'src/ko-templates',
// Destination directory for compiled index.html
dest: 'build'
}
};
// task definition here
gulp.task('html', function(){
// start from index.html
gulp.src(paths.html.main)
// Replace a placeholder comment with the output of a function...
.pipe(replace('<!-- ko-templates -->', (function(){
// walk through all template files...
var templates = [];
var files = fs.readdirSync(paths.html.templates);
for (var i in files) {
// Prepend and append each template's content with the Knockout
// template tag, including a unique ID based on the filename.
templates.push(
'<script type="text/html" id="' + path.basename(files[i], '.html') + '-template">' +
fs.readFileSync(paths.html.templates + '/' + files[i], 'utf8') +
'</script>'
);
}
// Return the templates separated by a break
return templates.join("\n");
}())))
// Plop the result to the build/destination path
.pipe(gulp.dest(paths.html.dest))
});
<!DOCTYPE html>
<html>
<body>
<p>Some normal content!</p>
<!-- ko-templates -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment