Sometimes it's useful to have global variables for templates.
Some examples could include things like:
I was thinking it would be cool to add something like:
var hbs = require("handlebars");
hbs.registerGlobal({
title: "myapp"
});
Which could be referenced in any template, perhaps via @global.title
, @title
or just title
.
Thoughts?
I was thinking about this more and I think creating an inline helper could do the what you want.
var hbs = require("handlebars");
var myGlobal = {
title: "myapp"
};
hbs.registerHelper('global', function(key){
return myGlobal[key];
});
{{! in your template }}
<div>{{global "title"}}</div>
And you can do whatever with myGlobal
You can
define('myGlobal', function(){
return {
title: "myapp"
};
});
...
var myGlobal = require('myGlobal');
myGlobal['newKey'] = 'something';
...
var hbs = require("handlebars");
var myGlobal = require('myGlobal');
hbs.registerHelper('global', function(key){
return myGlobal[key];
});
Naturally there's a drawback like you keys getting overwritten but that's all you.
Supporting this within Handlebars itself will require a lot of overhead for little gain, IMO.
There are a number of options like @rafde's helper suggestion or passing a the global in the data field, which should actually work with the proposed syntax above:
template(context, {data: {global: global}})
Should expose everything on window in {{@global.foo}}
, but I have not tested this and you'll need to validate that this does infact work.
@kpdecker template(context, {data: {global: global}})
is not explicitly documented.
The closest I've seen is template({}, {data: {level: Handlebars.logger.WARN}})
But the documentation doesn't mention that a 2nd parameter can be passed.
Our documentation is often lacking, but if you want to help improve, that would be awesome.
This is extensively tested: https://github.com/wycats/handlebars.js/blob/master/spec/data.js#L1
Why couldn't you do this by simply defining the key/value pair in a non-variable object?
glabalPair = {title: "Title"};
https://github.com/wycats/handlebars.js/blob/master/spec/data.js#L1 was the answer. Closing this but documentation should still be added.
Not documented yet?
Most helpful comment
@kpdecker
template(context, {data: {global: global}})
is not explicitly documented.The closest I've seen is
template({}, {data: {level: Handlebars.logger.WARN}})
But the documentation doesn't mention that a 2nd parameter can be passed.