Mixing dynamic/precompiled handlebar templates using assemble

2k Views Asked by At

I'm using Grunt and Assemble to create precompiled templates on my site but I need to dynamically create some sections based on information stored in client-side storage. Is there a way to exempt sections of a template from precompilation?

1

There are 1 best solutions below

1
On BEST ANSWER

We can't do custom delimiters (a shortcoming of Handlebars), but there are a couple of solutions that might work for you. Neither is necessarily idiomatic, so you be the judge of how suitable these are for the project you're working on.

string replacement

You could use some custom (temporary) delimiters for the templates in the content that shouldn't be compiled, then create a block helper that will convert those delimiters back to valid handlebars expressions during compile time (I tested this for this answer and it works):

For example:

Handlebars.registerHelper("raw", function(options) {
  return options.fn(this).replace(/\[\[/g, '{{').replace(/\]\]/g, '}}');
});

Then use it like this:

{{#raw}}
  {{> foo }}
{{/raw}}

Inside foo.hbs, you might have something like this:

<title>[[title]]</title>

and it will render to:

<title>{{title}}</title>

This solution is hacky for sure, and you might have problems if you happen have any code examples embedded in the included content and one of the examples happens to have that syntax (like [0,1,[foo, bar]].

escaping

This solution is most likely the better way to go. Handlebars will not evaluate any templates that are preceded by \. So you can do this:

<title>\{{title}}</title>

and it will render to:

<title>{{title}}</title>

The first suggestion probably wasn't even worth adding, but hey, you never know right?