Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access constant in an Ember template

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!

like image 264
chris_st Avatar asked Mar 06 '15 15:03

chris_st


2 Answers

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

like image 83
Marcio Junior Avatar answered Sep 28 '22 08:09

Marcio Junior


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'}}
like image 40
Gennady Dogaev Avatar answered Sep 28 '22 07:09

Gennady Dogaev