js.erb文件中Ruby代码的范围是什么,它如何访问控制器变量 [英] What is the scope of Ruby code in a js.erb file and how can it access controller variables

查看:84
本文介绍了js.erb文件中Ruby代码的范围是什么,它如何访问控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个js.erb文件,我想在其中使用asset_path。它包含在以下视图中:

I have a js.erb file in which I want to use asset_path. It is included in a view like this:

<%= javascript_include_tag "resources/gallery_resource" %>

这在资产路径是自包含的情况下工作正常,但是我需要使用在资产路径中的controller(@resource):

This works fine while the asset path is self contained, however I need to use a variable defined in the controller (@resource) inside the asset path:

element.image = "<%= asset_path 'resources/galleries/'+@resource.uid+'/'+index+'.jpg' %>"

@resource的问题未定义。那么如果Ruby代码无法访问控制器,那么它的范围是什么?我应该如何在这里提供变量?

The problem being @resource is not defined. So what is the scope of this Ruby code if it doesn't have access to the controller? And how should I make the variable available here?

我理解如何使Javascript可以访问变量,但我想让它可用于嵌入式Ruby。

推荐答案

您需要将其渲染为局部,并将资源作为本地传递:

You will need to render it as a partial, and pass the resource in as a local:

<script>
  <%= render :partial => 'resources/gallery_resource', :locals => { :resource => @resource } %>
</script>

此外,在gallery_resource.js.erb文件中,您需要将@resource更改为just resource :

Also, in the gallery_resource.js.erb file you'll need to change @resource to just resource:

element.image = "<%= asset_path 'resources/galleries/'+resource.uid+'/'+index+'.jpg' %>"

如果在任何其他操作中呈现它们,它们还需要传递:资源值:locals hash。

If this is rendered in any other actions, they will also need to pass a :resource value in the :locals hash.

js.erb文件的范围取决于以下几点:

The scope of the js.erb files depends on a couple of things:


  • 如果控制器本身正在渲染文件,那么它可以访问实例变量(如'@resource')。如果存在并且浏览器请求了js响应类型,那么views / viewtype / show.js.erb就是这种情况。就像.html.erb文件一样。

  • 如果它被渲染为部分,那么唯一的范围就是你传入的:locals hash。这些不是实例变量,而是局部变量,因此它们被引用(如'resource')。

  • 另一方面,使用javascript_include_tag在HTML中生成一个标记直接引用JS文件。如果你真的需要包含一些不可变的javascript,这没关系。这些要么必须位于app / assets /目录下的某个位置,要么位于您的公共/目录下。

app / assets或public /中的文件能够访问各个请求中的变量 - 他们或者不编译(公共/)或者它们只预编译一次(app / assets)。

Files in app/assets or in public/ are not able to access variables in individual requests - they either don't get compiled (public/) or else they're pre-compiled only once (app/assets).

据推测,有问题的文件目前在你的app / assets目录。为了将其渲染为局部,将其移动到views /目录下的某个位置,在名称前放置一个下划线(_):

Presumably, the file in question is currently in your app/assets directory. In order to render it as a partial, move it somewhere beneath the views/ directory, put an underscore (_) in front of the name:

app/views/resources/_gallery_resource.js.erb

这篇关于js.erb文件中Ruby代码的范围是什么,它如何访问控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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