如何在 app/assets/* 文件中访问控制器的变量 [英] How to access controller's variables in app/assets/* files

查看:39
本文介绍了如何在 app/assets/* 文件中访问控制器的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Rails 3.1.

I use Rails 3.1.

在我的 app/controllers/locations_controller.rb 中,我声明了一个 @location 变量

In my app/controllers/locations_controller.rb I declare a @location variable

@location = Location.find(params[:id])

我有一个文件 /app/assets/javascripts/locations.coffee.erb 我想在其中使用 @location 变量

I've a file /app/assets/javascripts/locations.coffee.erb where i want to use the @location variable

myLatlng: new google.maps.LatLng(<%=@location.latitude %>, <%=@location.longitude %>)

它不是开箱即用的,是否有任何解决方案可以实现该目标?

it's not working out of the box, is there any solution to achieve that goal?

推荐答案

对 Sprockets 提供的资产或系统上的任何资产的请求由一个完全独立的请求提供服务,因此它无法访问控制器中设置的实例变量.

A request to a Sprockets-provided asset, or really any asset on the system, is served by an entirely separate request and so it won't have access to the instance variables set up in the controller.

我要做的是将该 JS 放在由控制器视图呈现的某个部分中.这样它就可以访问这些变量.

What I would do is to have that JS in a partial somewhere that is rendered by the controller's view. That way it would have access to those variables.

这篇关于如何在 app/assets/* 文件中访问控制器的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆