David Moles
David Moles

Reputation: 51179

Embedding Handlebars templates in Backbone views, or possibly vice versa

I'm working on a Grails app with client-side Backbone views that use Handlebars templates. Right now the views in .js files and the templates are in .html files. The .js files are rolled up together into an application bundle file, which can be compressed, cached, etc. The .html files are inlined using the Include plugin and show up directly in the generated HTML source.

This has a couple of annoyances.

  1. for ease of development, I'd like to get these into a single file, so you don't have to find and open two files every time you want to work on a view, and you don't risk loading the .js but not including the .html or vice versa.
  2. I'd like the templates themselves to have the benefit of compression, caching and so on rather than being repeated every time we generate HTML.

I can see some ways to do (1) -- e.g., wrap the .js in a <script> tag and embed it directly in the .html -- but they lose the benefits of (2). I can see some ways to do (2) -- e.g., precompile the Handlebars templates with the Handlebars-Resources plugin and treat them like any other Javascript -- but that doesn't get you to (1).

I guess ideally I'd have the HTML embedded in the .js files. But I don't want inline strings; I want it to be clear to my IDE that the HTML is HTML, with all the completion and error-checking benefits that entails. Is there a clean way to do that? Or another alternative I haven't thought of?

Upvotes: 0

Views: 204

Answers (1)

jevakallio
jevakallio

Reputation: 35960

  1. From a code maintainability point of view embedding your view code into <script> tags would be a nightmare, and I doubt it would even work. Embedding HTML in a code file is even more horrifying. Even if you could hack together some setup with grep and duct tape, I'm pretty sure there's no IDE that would understand it and give you the syntax hightlighting you want.

    Just arrange your IDE windows/tabs next to each other and don't overthink it.

  2. Use the Handlebars precompilation support. It's great.

Upvotes: 1

Related Questions