How to check if a module/template is defined?


#1

I’m migrating my app to Ember CLI and previous I was using Grunt to build it and one of tasks compiled all templates into Ember.TEMPLATES hash. It made it easy to check if a template with given name exists. Now that templates are compiled to modules, how can I find if given template is defined?


#2

Assuming you’re in the context of an object that was instantiated from the container:

this.container.has('template:<name>');

Otherwise, you need to access the app container. devtools provides ways to do that for debugging purposes.

or if you just want which access to see which templates you have:

var templates = []; 
for(var moduleKey in require._eak_seen) { 
  if (moduleKey.indexOf('\/templates\/') !== -1) { 
    templates.push(moduleKey); 
  } 
}
console.log(templates);

Not sure what you’re trying to achieve, so can’t recommend one versus the other.


#3

Thanks!

I check for some stuff before the app is “ready” and set an error if one of these checks fails. Later in error route I check if there’s a specific template for this error and if there is, I render the error-specific template, otherwise I’m rendering a generic template with “there was an error” message.


#4

Ah, then in the error route check this.container.has is probably the approach you want.


#5

Is there a way to do this within component, I tried it in my component but I couldn’t access container from it(this.container returns undefined)!! You help will be much appreciated. Thanks.


#6

What version of ember?


#7

We are using ember 1.11.


#8

The container on the component is not the same contain as the rest of the application, this is by design. What I would do is create a service and inject that into my component which exposes a lookup method.

Example: http://jsbin.com/sawohiguva/1/edit?html,js,output


#9

Thanks for the jsbin, definitely looks like an elegant solution for the issue. thanks again. The only tiny thing I did was changed this.container.has(‘template:’ + templateName) to this.container.lookup(‘template:’+templateName) because I don’t know how to get “registry” to avoid the deprecation warning(https://github.com/emberjs/data/issues/2806)


#10

I’m curious why has has deprecation warnings when lookup does not. I guess I need to look closer at these changes.