Robert Mosolgo

To my knowledge, batman.js is not maintained. For that reason, I don't suggest that you use it for a new project!

Slim Templates With Batman.js and the Rails Asset Pipeline

You can use Slim (or Haml) to serve your Batman.js templates in the Rails Asset Pipeline.

1. Include Slim in your gemfile

Add this line to your Gemfile:

Gemfile
1
gem "slim"

2. Register the Slim engine with Rails

Make a new initializer (eg, config/initializers/slim_assets.rb) and put this in it:

config/initializers/slim_assets.rb
1
Rails.application.assets.register_engine('.slim', Slim::Template)

Credit: Dillon Buchanan

Update: Serving compiled Slim (or Haml) assets in production

When you deploy to production, if you have config.initialize_on_precompile = false, an initializer isn’t going to work. You’ll have to register the Sprockets engine another way. Add it to the application config in config/application.rb:

config/application.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module MyApp
  class Application < Rails::Application
    # ... config stuff ...
    config.before_initialize do |app|
      require 'sprockets'
      require 'slim'
      # require 'tilt' # for Haml
      Sprockets::Engines #force autoloading
      Sprockets.register_engine '.slim', Slim::Template
      # Sprockets.register_engine '.haml', Tilt::HamlTemplate # for Haml
    end
    # ... more config stuff ...
  end
end

Now, you’ll have the Slim template engine available even if your app doesn’t intialize, which is most notably the case for bundle exec rake assets:precompile. Nice!

3. Beef up your BatmanController

At time of writing, the batman-rails-generated BatmanController won’t work right in production. There’s an outstanding PR with a fix. If that’s closed, then we’re good to go. In the mean time, Make your app/controllers/batman_controller.rb look like this:

app/controllers/batman_controller.rb
1
2
3
4
5
6
7
8
9
10
11
class BatmanController < ApplicationController
  def index
    if request.xhr?
      prefix_length = Rails.application.config.assets.prefix.length + 1
      path = request.path[prefix_length..-1]
      render :text => Rails.application.assets[path]
    else
      render nothing: true, layout: 'batman'
    end
  end
end

When this is done, any files ending in .html.slim in assets will be served as rendered HTML in response to XHR (Ajax) requests. Note that all non-XHR requests will still receive the batman layout (but then Batman will respond to the request, so you’re all good).