简体   繁体   中英

How to add to a javascript var array using content_for in Ruby on Rails?

Right now in my code I'm calling content_for like...

<% content_for :javascript do -%> <%= "var boxplot_data=#{@survey.boxplot_answers.to_json};" %> <% end -%>

Rather then having to convert a whole array at once I'd rather add to the array boxplot_data and then have it display as a var. That way I can make my code easier to read because right now where I use that data in my partial isn't near where I generate it to add to the view.

I guess the best approach would be to define a helper:

def add_to_boxplot(val)
  @boxplot ||= []
  @boxplot << val
end

def json_boxplot
  "var boxplot_data = #{@boxplot.to_json}"
end

Then in your view just use add_to_boxplot and in your layout instead of yield(:javascript) use json_boxplot .

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