简体   繁体   中英

Generating JavaScript in Sinatra helpers

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 (ie 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 (eg :javascript ). The text in the filter is however subject to normal ruby string interpolation, ie anything inside #{} is executed as Ruby code.

So one way of getting your example to work would be something like:

:javascript
  var names = new Array;
  #{js = ""
  User.all.each {|u| js << "names.push(#{u})\n" }
  js}

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:

def js_array(name, array)
  js = "var #{name} = new Array();\n"
  array.each do |i|
    js << "#{name}.push(#{i})\n"
  end
  js
end

(Or you could create a literal javascript array:

def js_array(name, array)
  js = "var #{name} = ["
  js << array.collect{|i| "\"#{i}\""}.join(",")
  js << "]"
  js
end

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:

helpers do
  def js_array(name, array)
    js = "var #{name} = new Array();\n"
    array.each do |i|
      js << "#{name}.push(#{i})\n"
    end
    js
  end
end

With this in place, you can then do

:javascript
  #{js_array("names", User.all)}

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 :javascript filter 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:

:javascript
  #{js_array("names", User.all.collect(&:pretty_name)}

(where pretty_name is a method on the User object that returns a name for printing), or perhaps alter the helper method to extract the string you want to use.

Rather than having the helper method generate the JavaScript, you probably want it to return the array of names that can then be used as the source for the jQuery UI Autocomplete widget in the view.

So your helper method would look something like this:

helpers do
  # Return an array of users' names
  def get_all_names
    return User.all.map {|u| u.name}
  end
end

And in your Haml:

:javascript
  $(function() {
    var names = #{get_all_names.to_json};
    $("#widget").autocomplete({ source: names });
  }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM