Here comes the next post in the *Today I Learned* series! In each post, we discuss a quick tip or a solution to a problem our developers came across in their projects. This time, our developer Kuba explains how to render templates to strings in Ember.js. Enjoy!

Here comes the next post in the Today I Learned series! In each post, we discuss a quick tip or a solution to a problem our developers came across in their projects. This time, our developer Kuba explains how to render templates to strings in Ember.js. Enjoy!

Why Render Templates To Strings?

Think about a situation when you need to have a couple of predefined email templates that have dynamic content and must be previewed on the app before sending. Sometimes, it can be useful to render the template of the component or route to string.

Rendering templates to strings can be done with a simple string interpolation, but it will eventually be really hard to maintain and improve. The solution is to make components that have templates with your predefined content and dynamic bindings. Afterwards, you can render the component's template to string and show it in the app.

Rendering A Template Without Any Dependencies

A simple situation requires rendering a template that does not have any dependencies such as other components or helpers. To do so, you need an Ember.View instance with a mocked Ember.Component instance that holds your dynamic content. This is exactly what I have done here:

Hi! This is some template with dynamic content from Today I Learned: Rendering Templates To Strings In Ember.js

Rendering A Template With Dependencies

If you need to include any dependencies in your component, e.g. helpers, you need to use Ember’s injected method createChildView . Take a look:

Hi! This is some template with dynamic content from Today I Learned: Rendering Templates To Strings In Ember.js and helper inside -

That’s a very quick and straightforward approach to the topic, but of course, there’s more to read about it. A very extensive explanation about why we need to use createElement , which is not defined specifically for that case, can be found in this GitHub thread.

Are you going to use this solution in your code? Or maybe you can share with other tips and tricks regarding templates in Ember.js? Feel free to leave some comments. We’ll be happy to hear from you!

Are you an Ember.js enthusiast yearning to learn new things? Check out our Ember Run Loop ebook and learn how to streamline your work with the code!