Last active
July 10, 2021 03:13
-
-
Save seanlinsley/23758785a20805ea06b433696129b21c to your computer and use it in GitHub Desktop.
Handlebars + ERB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Backbone.View.extend({ | |
template: Handlebars.compile( | |
<%= embed('template.hbs').inspect %> | |
// some .hbs.erb files are also loaded | |
), | |
// ... | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you saved my day!