Access constant in an Ember template

此生再无相见时 提交于 2019-12-05 10:46:31

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');

I faced the same problem and solved it by creating a helper, that can read configuration file:

//...app/helpers/read-env.js
import Ember from 'ember';
import ENV from '../config/environment';

export function readEnv(params/*, hash*/) {
  if (params.length === 0) {
    return undefined;
  }

  return Ember.Object.create(ENV).get(params[0]);
}

export default Ember.Helper.helper(readEnv);

Constants defined like this:

ENV.CATEGORY = {
  'CATEGORY_1': 0,
  'CATEGORY_2': 1
};

In template I use it like this:

{{read-env 'CATEGORY.CATEGORY_1'}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!