I’m using Haml as my templating language in a Sinatra-based web application, and I’m having trouble generating a JavaScript array based on information from a database model. Essentially, I’m trying to generate a JavaScript array made up of user names for use in a jQuery-UI Autocomplete widget.
I tried the following code, but it didn’t work.
:javascript
var names = new Array;
- User.all.each do |u|
names.push(#{u})
After reading, most people suggest doing anything that involves evalutating Ruby (i.e. anything prefixed with ‘-‘ in Haml) in a helper instead. So, given this, can anyone explain to me how to generate JavaScript in a helper method?
The problem here is that you can’t use normal haml features within a filter (e.g.
:javascript). The text in the filter is however subject to normal ruby string interpolation, i.e. anything inside#{}is executed as Ruby code.So one way of getting your example to work would be something like:
This is pretty messy though, and the way to tidy it up is to move it into a helper. A helper is just a method that is in scope during rendering (so it is available to be called in the haml file), and generates some text to be included in the generated page.
In this case you’re generating javascript, but javascript is just text, so there’s no problem there. The helper method could look something like this:
(Or you could create a literal javascript array:
if you preferred.)
Next, where does this method go? In Sinatra you define helper methods using the ‘helpers` method. Any methods defined in this block will be available in your views:
With this in place, you can then do
in your haml to generate your javascript array. Note that you still need the
#{}so that the ruby code will be executed, only now you just have a single method call between the braces. The:javascriptfilter will wrap the block in<script>and<![CDATA[tags, and the helper will create the actual javascript you want.One more thing: in your example the array is
User.all, which looks like a call to activerecord or something similiar, in which case you might not have an array of strings but of some other object that might not give the result you want. You might need to do something like:(where
pretty_nameis a method on theUserobject that returns a name for printing), or perhaps alter the helper method to extract the string you want to use.