Ruby on Rails - 将JavaScript变量从控制器发送到外部Javascript资产文件 [英] Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file
问题描述
我正在Ruby on Rails中创建一个网站。我有一个控制器动作,呈现如下视图:
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
这很好,因为它呈现了节目我喜欢.html.erb。但是我想以某种方式将time_left作为Javascript变量传递给视图,因为这个值被倒计时JQuery插件使用。
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.
我可以在页面上放置一个javascript块在HTML中并像这样打印一个实例变量:
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>
但是我想将我的所有JS保存在外部文件中,并且页面外可以有人给出一些关于如何实现这个的建议?
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?
推荐答案
是的,你可以!
用一个参数(timelimit)将JS代码重写为函数,并将其放入一些外部文件中。然后你可以从视图中调用函数并将 @timeleft
变量作为JS函数参数传递。
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 @timeleft
variable as JS function argument.
简短示例:
#controller
@time_left = Time.now.to_i - 3.hours.to_i
。
#javascript
function count_down(time_left) {
$('#countdown').countdown(time_left)
}
。
#view
<%=javascript_tag "count_down(#{@time_left})" -%>
示例未经过测试,只是想法不完整解决方案。不要忘记加载该JS文件。您可以使用其他JS轨帮手 javascript_include_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.
这篇关于Ruby on Rails - 将JavaScript变量从控制器发送到外部Javascript资产文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!