Last active
February 15, 2021 22:18
-
-
Save amatiasq/4944035 to your computer and use it in GitHub Desktop.
A simple RequireJS plugin to include Handlebars templates
This file contains 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
define(function(require) { | |
var text = require('text'); | |
var view = require('view'); | |
var cache = {}; | |
function load(name, parentRequire, done, config) { | |
text.load(name, parentRequire, function(template) { | |
cache[name] = template; | |
done(view(template)); | |
}, config); | |
} | |
function write(pluginName, moduleName, write, config) { | |
write.asModule(pluginName + "!" + moduleName, [ | |
"define([ 'view' ], function(view) {", | |
"return view('", | |
text.jsEscape(cache[moduleName]), | |
"');", | |
"});" | |
].join("")); | |
} | |
return { | |
load: load, | |
write: write, | |
}; | |
}); |
This file contains 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
define(function(require) { | |
var _ = require('underscore'); | |
var Handlebars = require('handlebars'); | |
/************** | |
* HANDLEBARS * | |
**************/ | |
Handlebars.registerHelper('equals', function(value, expected, options) { | |
return Handlebars.helpers['if'].call(this, value == expected, options); | |
}); | |
Handlebars.registerHelper('unless_equals', function(value, expected, options) { | |
return Handlebars.helpers['unless'].call(this, value == expected, options); | |
}); | |
Handlebars.registerHelper('if_contains', function(value, expected, options) { | |
return Handlebars.helpers['if'].call(this, value && (value.indexOf(expected) !== -1), options); | |
}); | |
Handlebars.registerHelper('unless_contains', function(value, expected, options) { | |
return Handlebars.helpers['unless'].call(this, value && (value.indexOf(expected) !== -1), options); | |
}); | |
Handlebars.registerHelper('date', function(value, format) { | |
var date = typeof value === 'number' ? moment.unix(value) : moment(value); | |
if (format === 'from now') | |
return date.fromNow(); | |
return date.format(typeof format === 'string' ? format : 'L') | |
}); | |
/***************** | |
* VIEW FUNCTION * | |
*****************/ | |
return function(text, callback) { | |
var compiled = Handlebars.compile(text); | |
return function(data) { | |
if (arguments.length > 1) | |
data = _.extend.apply(_, [{}].concat(_.toArray(arguments))); | |
return compiled(data || {}); | |
}; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It depends on RequireJS's text! plugin.