Global variable

How to set a variable so that it can be accessed from every template directly?

You have a couple options, which one you use depends on your use case. Off the top of my head you could…

  1. Store the variable in a service and use an initializer to inject the service in every controller. This would only work with route templates…so you could also auto-inject the service into components as well if you wanted that

  2. Store the variable in a service and write a helper which injects the service and simply returns the value

In general though the explicitness of data declaration and injection is encouraged so I wouldn’t do something like this unless it was necessary and had a very specific use case.


If you just want a hard-coded value, return it from a helper:

import { helper } from '@ember/component/helper';

export default helper(function globalTitle() {
  return "This is Our Global Title";
{{! use it like this:}}

{{! or like this: }}
<SomeComponent @title={{our-global-title}} />

If you need to change it over time, use @dknutsen’s suggestion of a helper that injects a service. Services are the place to store shared global state.

1 Like

Thank you for suggestions.That helps me a lot. I need to get the value of key from json object in template.The problem is the key contains “.” character in it.I am not able to access the value using object.key

you can use “get” helper. BTW you can store global variable in environment object, and access it thru helper

pls write simple example here …