Expose Handlebars object for extension
bookwyrm opened this issue · 9 comments
I've got a situation where I want to use the same set of SVG icons in both HTML (via data attributes) and CSS (via Sass magic). I figured out a way to [ab]use the previewTemplate
option to output a set of Sass lists where each list is comprised of a group of Sass variables which I then use like a standard image sprite via some Sass functions/mixins. These variables are built by [ab]using the template
option. This mostly works but I've run into an issue where I need the image type to be a part of the Sass variable name.
I figured that I could solve it by adding a new helper to the Handlebars
object in directory-coder.js but I didn't see any way that I could get access to the Handlebars object in order to extend it. I ended up just dropping my helper registration right into the _loadTemplate
function which works for me on this one project but not moving forward.
Is there any way that the Handlebars object could be made available as some kind of a callback or something in the Gruntfile so that it can be extended easily?
@aminta, not a clean way...I ended up just patching directory-encoder.js
locally and updating my project documentation with a step to apply the patch.
--- lib/directory-encoder.js
+++ lib/directory-encoder.js
@@ -174,6 +174,15 @@
if( fs.existsSync( templateFile ) && fs.lstatSync( templateFile ).isFile() ){
var source = fs.readFileSync( templateFile ).toString( 'utf-8' );
+ Handlebars.registerHelper('data-type', function(arg) {
+ if ( arg.indexOf('image/svg') !== -1 ) {
+ return 'svg';
+ } else if ( arg.indexOf('image/png') !== -1 ) {
+ return 'png';
+ } else {
+ return 'png-fallback';
+ }
+ });
tmpl = Handlebars.compile(source);
} else {
throw new Error( "Template file either doesn't exist or isn't a file" );
patch -p0 -d node_modules/directory-encoder < grunticon/directory-encoder.patch
Sorry @bookwyrm, me too I had added a new helper after var source = [...] but it return me a "Missing helper: " if I add my helper to .hbs file. Any help?
Ok, it works, maybe previously I made a typo! Thanks for the hint!
By the way, in directory-encoder.js I've added
var Handlebars = require( 'handlebars' );
var helpers = require('handlebars-helpers');
after
var Handlebars = require( 'handlebars' );
to use Handlebar Helpers in my project and it works, if this can help...
@bookwyrm sorry i'm late as ridiculously late to this as I am. Exposing the handlebars object doesn't sound like a bad idea. Unfortunately, as you might have guessed, i'm currently in no shape to make this change right now.
If you PR something in and make sure it passes tests, I would be completely happy to merge it, though.
@jefflembeck Is there anything I could do to help progress this? Would really love to add my own helper functions.
Looks like this shipped? Closing.