Oxymoron
Oxymoron

Reputation:

How can I render Ruby code in javascript?

I have a javascript part in my view, that I want to modify through locals I have defined in a helper.

<script type="text/javascript">
var store = new Ext.data.JsonStore({
    url: '/admin/administration/users/grid_data.json',
    root: 'users',
    fields: [
    <%- for field in fields do -%>
       {name: '<%= field[:data_index] -%>'},
    <%- end -%>
    ]
});
</script>

This doesn't work, can you help me?

Upvotes: 1

Views: 1345

Answers (4)

mixonic
mixonic

Reputation: 2701

This script won't work in IE becuase of it's strict Javascript parser. The for loop in your code leaves a trailing , at the end of the array. That's not a valid Javascript syntax. The easiest way to move data from ruby into javascript is almost always to_json:

<% javascript_tag do %>
var store = new Ext.data.JsonStore({
    url: '/admin/administration/users/grid_data.json',
    root: 'users',
    fields: <%= fields.collect{|f| { :name => f[:data_index] } }.to_json %>
});
<% end %>

And you can leave out the .collect{|f| { :name => f[:data_index] } } if you use the same hash key in Ruby and Javascript. Much nicer, and much less prone to bugs.

Good luck!

Upvotes: 4

Reuben Mallaby
Reuben Mallaby

Reputation: 5767

What about:

<%= (fields.collect {|field| "{name: #{field[:data_index]}}"}).join(',') %>

Upvotes: 0

Mohsin Shafique
Mohsin Shafique

Reputation: 935

First thing is to look at the generated code from the page source. Any syntax errors there? Is Ext library included somewhere in the head section of the HTML?

Upvotes: 0

wgpubs
wgpubs

Reputation: 8271

The problem is that you are going to have a trailing comma. You need to check the lenght of your field array and if it is the last element simply do not include the comma you currently have at the end of every name parameter.

Upvotes: 1

Related Questions