Skip to content

Instantly share code, notes, and snippets.

@reu
Last active August 29, 2015 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/ef8a5b38768b519fca42 to your computer and use it in GitHub Desktop.
Save reu/ef8a5b38768b519fca42 to your computer and use it in GitHub Desktop.
Gulp plugin to pre-process HTML template includes.

Gulp Template

This plugin allows you to directly include HTML templates into a Javascript file.

Example

Given the following template:

template.html

<h1 class="title">
  <b>Hellow world</b>
</h1>

You can assign it to a variable using the following method:

var template = /* @include template.html */
var fs = require("fs");
var mapStream = require("map-stream");
module.exports = function preProcessTemplate(options) {
options = options || {};
function doubleQuote(string) { return '"' + string + '"' }
function notBlank(string) { return string.trim() != "" }
return mapStream(function(file, callback) {
if (file.isNull()) return callback(null, file);
var includePath = options.includePath || path.dirname(file.path);
var contents = file.contents.toString("utf-8");
file.contents = new Buffer(contents.replace(/\/\*\s*@include\s+([^\*]+)\*\//, function(match, fileName) {
var filePath = path.join(includePath, fileName.trim());
return fs
.readFileSync(filePath)
.toString("utf-8")
.replace(/"/g, "\\\"")
.split("\n")
.filter(notBlank)
.map(doubleQuote)
.join(" + ");
}));
callback(null, file);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment