I am creating a website in Ruby on Rails. I have a controller action that renders a view like so:
def show
time_left = Time.now.to_i - 3.hours.to_i
@character = current_user.characters.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @character }
end
end
This is fine as it renders the show.html.erb as I like. I would like however to somehow pass time_left to the view as a Javascript variable as this value is use by a countdown JQuery plugin.
I could put a javascript block on the page in the HTML and print a instance variable out like so:
<script type="javascript"> $('#countdown').countdown('<%= @time_left =>')</script>
But I would like to keep all my JS in a external file and off the page could anyone give some advice on how to implement this?
Yes, you can!
Rewrite your JS code into function with one argument (timelimit) and put it into some external file. Then you can call the function from view and pass that
@timeleftvariable as JS function argument.Short example:
.
.
javascript_tag
Example not tested, it is only idea not complete solution. Don’t forget to load that JS file. You can use other JS rails helper javascript_include_tag.