Inline Templates in Angular: Quick Tip

Dave Ceddia bio photo By Dave Ceddia Comment

You may find yourself using inline templates in your directive definitions from time to time.

But it’s kind of painful, right? String concatenation sucks. Putting everything on one line sucks even more.

Do your directive templates look like this?

	'<h1>This template brought to you by:' +
		'<span>string concatenation!</span>' +

Or this?

template: '<h1>This template brought to you by: <span>one really long line</span></h1>'

Here’s a better way

If you’re using ES5, put each line into an array and join them.

	['<h1>This template brought to you by:',

Better yet, if you’re already using ES6, use the new natively-supported multiline string. Just surround with backticks:

template: `
	<h1>This template brought to you by:

This has the added benefit of being able to interpolate values inside the strings like this:

`Hello ${name}!`

Choosing a framework is difficult.

Learning React? Sign up and get my React Learning Timeline PDF, and also weekly-ish articles about React, Angular, and JavaScript.

A few emails per month — unsubscribe any time.
comments powered by Disqus