Dillon Buchanan

Software Engineer

Hello there! I'm Dillon Buchanan, a software developer and all-around programming enthusist working in Boston. I love creating great software!

Rails: Slim Templates in the Asset Pipeline

I hate writing plain HTML these days. With the advent of templating engines like Slim it's really made it hard to ever go back to writing plain HTML. In many of my projects I commonly use a Javascript framework like AngularJS which heavily depends on view templates. To make things easier I generally put all my views in the asset folder - but uh-oh, out of the box it looks like I can't use Slim to create my templates! Well there's a simple fix to get this to work.

The Problem

If you've ever stuck a Slim file in the assets folder and attempted to access it via it's base extension you'll know it doesn't work quite like you'd probably expect. If I have a file called '/assets/app/templates/test.html.slim' I can only access it if I go to that exact path in the browser and even then it's still in Slim format. The ideal outcome is to be able to access '/assets/app/templates/test.html' and for the engine to respond with HTML. Here's how we fix that.

The Fix

  1. Create a file in the '/config/initializers/' directory called 'slim_assets.rb' (or what ever you want to call the file - it doesn't matter). 
  2. Within that file, paste the following code:
    Rails.application.assets.register_engine('.slim', Slim::Template)

    This piece of code will register the '.slim' extension in our asset pipeline. Now, when we see a '.slim' file it will activate the Slim:template engine and all will be good.

  3. Restart the server and try accessing the file in the browser.


With any luck, you'll now see the HTML counterparts for the Slim templates in your asset pipeline! For completeness sake, I am using Rails 3.2.12 with Slim 1.3.6.


comments powered by Disqus