问题描述
如何指定一个自定义配置变量以用于句柄模板?
How would one specify a custom config variable for use in the handlebars template?
例如:
// config/settings.json
{
"title": "Hello World"
}
// config/foo.json
{
"bar": "baz"
}
// Template
{{ settings.title }}
{{ foo.bar }}
推荐答案
您需要使用依赖注入来将全局变量注入到控制器中。来自Balint Erdi的它很好。
这基本上是你do
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
-
创建2个对象 - 设置和foo。
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');
这是上述2的完整代码初始化程序中的步骤
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}}
这篇关于Emberjs自定义配置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!