在Ember模板中访问常量 [英] Access constant in an Ember template
问题描述
我有以下模板,我想要有三个任务项目列表
组件实例,每个实例用于不同的 taskState
值。显然,我想摆脱魔术数字。
< h4>任务:< / h4>
< div>< h5> Backlog:< / h5>
{{task-item-list tasks = model taskState = 101}}
< / div>
< div>< h5>工作:< / h5>
{{task-item-list tasks = model taskState = 202}}
< / div>
< div>< h5>完成!< / h5>
{{task-item-list tasks = model taskState = 303}}
< / div>
感谢这个讨论我可以在我的 config / environment.js
文件中定义常量,并使用它们模型,测试等,但不能(尽可能接近我的)在我的模板。
有没有办法使用常量,还是有更好的这样做吗?我可以看到子类化组件,但我不认为这是一个很好的解决方案。
谢谢!
您是否尝试在组件中注入env?这样的一个例子:
app / initializers / inject-env.js
从../config/environment导入env;
export函数initialize(container,application){
application.register('env:main',env,{singleton:true,instantiate:false});
application.inject('component','env','env:main');
}
export default {
name:'inject-env',
initialize:initialize
};
然后在任何组件中,您将可以获取 config的内容使用
例如 env
属性的/environment.js {{env.environment}}
将显示当前环境。
如果你想注入您的任务项目列表
组件而不是所有组件,您可以使用:
application.inject('component:task-item-list','env','env:main');
Not sure what the proper "Ember Way" is to do this.
I have the following template, where I want to have three task-item-list
component instances, each for a different taskState
value. Obviously, I would like to get rid of the magic numbers.
<h4>Tasks:</h4>
<div><h5>Backlog:</h5>
{{ task-item-list tasks=model taskState=101 }}
</div>
<div><h5>Working:</h5>
{{ task-item-list tasks=model taskState=202 }}
</div>
<div><h5>Done!</h5>
{{ task-item-list tasks=model taskState=303 }}
</div>
Thanks to this discussion I can define constants in my config/environment.js
file and use them in models, test, etc., but not (as near as I can tell) in my templates.
Is there a way to use the constants, or is there a better way to do this? I can see subclassing the component, but I don't think that's a great solution.
Thanks!
Have you tried to inject the env in your components? Something like this:
app/initializers/inject-env.js
import env from '../config/environment';
export function initialize(container, application) {
application.register('env:main', env, { singleton: true, instantiate: false });
application.inject('component', 'env', 'env:main');
}
export default {
name: 'inject-env',
initialize: initialize
};
And then in any component you will be able to get the contents of config/environment.js
using the env
property. For instance {{env.environment}}
will show the current environment.
If you want to inject just in your task-item-list
component instead of all components, you can use:
application.inject('component:task-item-list', 'env', 'env:main');
这篇关于在Ember模板中访问常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!