Skip to content

Instantly share code, notes, and snippets.

@chytreg
Created August 3, 2011 17:51
Show Gist options
  • Save chytreg/1123289 to your computer and use it in GitHub Desktop.
Save chytreg/1123289 to your computer and use it in GitHub Desktop.
hjs sprocket template, put in your rails3 app as initializer
require 'tilt'
module Sprockets
# Tilt engine class for the Hjs compiler. Depends on the `Haml` and `ejs` gem.
class HjsTemplate < Tilt::Template
# Check to see if HAML is loaded
def self.engine_initialized?
defined? HAML && defined? ::Eco
end
# Autoload ejs library. If the library isn't loaded, Tilt will produce
# a thread safetly warning. If you intend to use `.ejs` files, you
# should explicitly require it.
def initialize_engine
require_template_library 'eco'
end
def prepare
end
# Compile template data with EJS compiler.
#
# Returns a JS function definition String. The result should be
# assigned to a JS variable.
#
# # => "function(obj){...}"
#
def evaluate(scope, locals, &block)
data.force_encoding("UTF-8") if data.respond_to?(:force_encoding)
context = Object.new
class << context
include Haml::Helpers
include ActionView::Helpers
def erb str, &block
return "<%#{str}%>" unless block_given?
erb("#{str}") + capture_haml(&block).chomp
end
end
Eco.compile CGI.unescapeHTML("#{Haml::Engine.new(data).render(context)}")
end
end
end
- puts this in application.rb
# Sprockets::HjsTemplate
Sprockets.register_engine '.hjs', Sprockets::HjsTemplate
- add those gems in Gemfile:
gem 'haml'
gem 'eco'
Then use can use templates like this:
%h1 Edit post
%form#edit-post{:name => "post"}
= erb 'if @title:' do
.field
= erb 'if false:' do
= label_tag :title
= erb 'end'
= text_field_tag :title, erb('=@title')
= erb 'else:' do
.field
= label_tag :content
= text_field_tag :content, erb('=@content')
= erb 'end'
.actions
= submit_tag "Update post"
= link_to 'Back1asd', "#/index"
@JaredSartin
Copy link

Where does the hjs_template.rb live?

@madsheep
Copy link

config/initializers i guess :)

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