Ben Emson

Create Sinatra Partials The Rails Way

This is just a quick post. I've been playing around with the Sinatra micro web framework, and have to say that it is excellent. It really is the perfect tool for rapidly creating small and useful Ruby micro-sites.

Being small and lightweight it doesn't have many of the features of larger frameworks like Ruby on Rails. One of the features I've begun to need is the handling of Rails like partials.

Notably I need to pass both local variables and collections to the partial code and have the partials rendered accordingly. I started implementing my own version, and then came across a nice little Github project: Sinatra-Helpers by sbfaulkner.

Anyway here is the code he uses for Sinatra partials: Liquid error: No such file or directory - posix_spawnp

You can use his project or if you just need this feature just pop this code into your Sinatra helpers file application_helper.rb: Liquid error: No such file or directory - posix_spawnp

Now you can call the partial from a your page e.g. index.haml Liquid error: No such file or directory - posix_spawnp

Create a partial in the same directory as the calling page. Note that this code doesn't like filenames truncated with a '-', so avoid this if possible. Also like in Rails your partials should start with an underscore. e.g. _mypartial.haml

To access the variable from this partial simply call the local variable name in your code: Liquid error: No such file or directory - posix_spawnp

Handling collections, again, is similar to the way Rails handles partial collections. From your page call the partial with a collection such as: Liquid error: No such file or directory - posix_spawnp

Now in the _listitem.haml partial code simply provide the partial name as a variable or the partialname with _counter for the increment number e.g. Liquid error: No such file or directory - posix_spawnp

Anyway all pretty basic stuff but I hope it helps the casual Sinatra surfer.

Goodluck.

blog comments powered by Disqus