问题
How would one specify a custom config variable for use in the handlebars template?
For example:
// config/settings.json
{
"title": "Hello World"
}
// config/foo.json
{
"bar": "baz"
}
// Template
{{ settings.title }}
{{ foo.bar }}
回答1:
You need to use dependency injection to inject you global variables into the controller. This blog post from Balint Erdi explains it well. Here is a working demo. This is basically what you do
Create 2 object - settings and foo.
var settings = Ember.Object.extend({ title: 'Hello World' }); var foo = Ember.Object.extend({ bar: 'baz' });
Register these 2 objects in the container using an application initializer.
container.register('globals:settings', settings, { singleton: true }); container.register('globals:foo', foo, { singleton: true });
Inject the 2 registered object into all the controllers.
application.inject('controller', 'settings', 'globals:settings'); application.inject('controller', 'foo', 'globals:foo');
Here's is the complete code for the above 2 steps in an initializer
Ember.Application.initializer({
name: "globals",
initialize: function(container, application) {
container.register('globals:settings', settings, { singleton: true });
container.register('globals:foo', foo, { singleton: true });
application.inject('controller', 'settings', 'globals:settings');
application.inject('controller', 'foo', 'globals:foo');
}
});
You can then reference the values in your template as
{{settings.title}}
来源:https://stackoverflow.com/questions/23802629/emberjs-custom-config-variables