Templates for component add-ons


#1

The guide for creating addons is clear about where a component’s javascript should go (addon/components/my-component.js) and how to import that to the consuming app via app/components/my-component.js, but it seems to be silent on the issue of where the template file goes and how it is made accessible to the consuming app.

I realize that the app directory is merged with the consuming application’s namespace, so it seems likely, even if unstated, that you can put your template in app/templates/components/my-component.hbs. However when I look at a couple of component addons in the wild I see some different approaches that aren’t really clear to me. For example…

emberx-select

There is no template in /app/templates/components, but in /app/templates/components/emberx-select.js we have this:

export { default } from 'emberx-select/templates/components/x-select';

while the template itself is actually in /addons/templates/current/components/emberx-select.hbs

I’m not sure how emberx-select/templates/components/x-select resolves to the actual template file, if that is in fact what is happening, but leaving that aside, is this exporting a handlebars file? I’m not sure I understand what that even means. And where does it get imported?

ember-inline-edit

Again there is no template in app/templates/components. Instead, the template is in addon/templates/components/ember-inline-edit.hbs, while in addon/components/ember-inline-edit.js we have this:

import Ember from 'ember';
import layout from '../templates/components/ember-inline-edit';
  ...
export default Ember.Component.extend({
  layout,
  ...
}

Not really sure what to make of this. Again, importing a handlebars file? Not sure what that means. There is an apparently deprecated layout property in Ember.component's parent View class, but it’s not clear that that’s what is being used here.

Any insights into these examples and clarification on what recommended best practice is would be much appreciated.


Ember-cli addon with template
#2

It goes in addon/templates/components/my-component.js. It should be explicitly mentioned, but if you use ember g, it’ll correctly generate both the JavaScript and the Handlebars file for you.

Because the template file is in addon/, which is the addon namespace.

Yup, Handlebars templates basically get pre-compiled to JavaScript modules.

export { default } from 'path'; is kind of a shorthand for importing and re-exporting the path module. It’s very confusing the first times you see it!

Yup! See above comment about pre-compilation :slight_smile:

I’m reviewing API documentation, and this is on the list. You can also see some people defining templates inline with the hbs tagged template string.