Inline Templates in Angular: Quick Tip

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?

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

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.

...
template:
	['<h1>This template brought to you by:',
	  '<span>arrays!</span>',
	 '</h1>'].join('')
...

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:
		<span>ES6!</span>
	</h1>
`
...

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

`Hello ${name}!`

Learning React can be a struggle -- so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, read my book Pure React.

Loved it! Very well written and put together. Love that you focused only on React. Wish I had stumbled onto your book first before I messed around with all those scary "boilerplate" projects.
— John Lyon-Smith
comments powered by Disqus