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:
: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.