Skip to content

Instantly share code, notes, and snippets.

@seanlinsley
Last active July 10, 2021 03:13
Show Gist options
  • Select an option

  • Save seanlinsley/23758785a20805ea06b433696129b21c to your computer and use it in GitHub Desktop.

Select an option

Save seanlinsley/23758785a20805ea06b433696129b21c to your computer and use it in GitHub Desktop.
Handlebars + ERB
Backbone.View.extend({
template: Handlebars.compile(
<%= embed('template.hbs').inspect %>
// some .hbs.erb files are also loaded
),
// ...
})
#
# Makes it possible to embed Handlebars templates & SVG images directly in our JS source.
# They're registered with Sprockets, so it can reload them when they're modified.
# `asset_data_uri` is similar but it base-64 encodes them, which breaks compression.
#
env.register_mime_type 'text/x-handlebars-template', extensions: ['.hbs']
env.context_class.instance_exec do
def embed(file)
path = resolve file, pipeline: :self
path = "file://#{path}"
# Without this we get errors like `could not convert "image/svg+xml" to nil`
types = {'hbs' => 'text/x-handlebars-template', 'svg' => 'image/svg+xml'}
if type = types[file.split('.').last]
path += "?type=#{type}"
end
asset = load path
asset.source
end
end
#
# Makes it possible to embed Handlebars templates & SVG images directly in our JS source.
# They're registered with Sprockets, so it can reload them when they're modified.
# `asset_data_uri` is similar but it base-64 encodes them, which breaks compression.
#
env.register_mime_type 'text/x-handlebars-template', extensions: ['.hbs.erb', '.hbs']
# trying to emulate https://github.com/rails/sprockets/blob/3224a80e833f43885b0870509ffdd3fd00109076/lib/sprockets.rb#L179
env.register_transformer_suffix ['text/x-handlebars-template'], 'application/\2+ruby', '.erb', Sprockets::ERBProcessor
env.context_class.instance_exec do
def embed(path)
asset = depend_on_asset(path)
asset.source
end
end
@serggl
Copy link
Copy Markdown

serggl commented Oct 1, 2020

you saved my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment