Skip to content

Instantly share code, notes, and snippets.

@rchampourlier
Created July 23, 2012 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rchampourlier/3162768 to your computer and use it in GitHub Desktop.
Save rchampourlier/3162768 to your computer and use it in GitHub Desktop.
Sinatra extension to render HAML to JST assets
require 'sinatra/base'
module Sinatra
module JstHamlAssets
module Helpers
def not_found
[404, 'JST Haml template not found']
end
def compile_jst_haml_template(name, path)
string = File.open(path).read
html = Haml::Engine.new(string, {:escape_attrs => false}).render
%{
$(function() {
var c = {};
if (!window.JST) window.JST = {};
JST[#{name.inspect}] = function() {
if (!c[#{name.inspect}]) c[#{name.inspect}] = _.template(#{html.inspect});
return c[#{name.inspect}].apply(this, arguments);
};
});
}
end
end
def self.registered(app)
app.helpers JstHamlAssets::Helpers
app.get '/jst/:template_name.jst' do
content_type 'application/javascript'
template_format = 'jst'
template_name = params[:template_name]
template_path = File.join(settings.root, 'views', 'templates', "#{template_name}.#{template_format}.haml")
not_found
if File.exist?(template_path)
compile_jst_haml_template(template_name, template_path)
else
not_found
end
end
end
end
register JstHamlAssets
end
class SinatraApp < Sinatra::Base
...
register Sinatra::JstHamlAssets
...
end
@rchampourlier
Copy link
Author

Added option to Haml::Engine.new so that attributes don't get escaped

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