Core template compilation functionality that transforms HTMLBars template strings and files into JavaScript TemplateFactory objects for Ember.js applications.
The main template compilation function with support for both tagged template literals and explicit string compilation.
/**
* Compile a template string or tagged template literal into a TemplateFactory
* @param template - Template string or tagged template literal
* @param options - Optional compilation options
* @returns TemplateFactory for use with Ember's template system
*/
function hbs(template: string, options?: PrecompileOptions): TemplateFactory;
function hbs(tagged: TemplateStringsArray): TemplateFactory;
interface PrecompileOptions {
/** Module name for template debugging and identification */
moduleName?: string;
/** Parser-specific options */
parseOptions?: {
/** Source name for error reporting */
srcName?: string;
};
}
/**
* Opaque type representing a compiled template
* Can only be constructed via hbs() function
*/
declare class TemplateFactory {
private readonly [Data]: 'template-factory';
}Usage Examples:
import { hbs } from 'ember-cli-htmlbars';
import { render } from '@ember/test-helpers';
import { setComponentTemplate } from '@ember/component';
// Tagged template literal (most common in tests)
await render(hbs`
<MyComponent @title="Hello" @items={{this.items}} />
`);
// String with options (useful for dynamic templates)
const template = hbs('<p>{{message}}</p>', {
moduleName: 'components/message-display.hbs'
});
// Component template association
class MyComponent extends Component {
greeting = 'Hello World';
}
setComponentTemplate(
hbs('<h1>{{this.greeting}}</h1>', {
moduleName: 'components/my-component.hbs'
}),
MyComponent
);The addon handles lower-level template compilation internally through the templateCompiler.precompile method from ember-template-compiler.js. This process is handled automatically by the hbs() function and Broccoli plugin and is not directly exposed as a public API.
The template compilation system transforms .hbs files into JavaScript modules:
// Input: component.hbs
<h1>{{@title}}</h1>
<p>{{@description}}</p>
// Output: component.js
import { hbs } from 'ember-cli-htmlbars';
export default hbs('<h1>{{@title}}</h1><p>{{@description}}</p>', {
moduleName: 'components/component.hbs'
});The addon provides Babel plugin integration for compile-time template processing:
// Source code
import { hbs } from 'ember-cli-htmlbars';
const template = hbs`<div>{{name}}</div>`;
// Compiled output (simplified)
const template = Ember.HTMLBars.template(/* compiled template function */);Template compilation errors are reported with detailed information including:
// Example error handling in tests
try {
await render(hbs`<InvalidComponent`);
} catch (error) {
// Error includes template source location and parsing details
console.log(error.message); // "Parse error on line 1..."
}