如何访问只能部分访问的Rails变量? [英] How do I access a rails variable that is only accessible to a partial?

查看:48
本文介绍了如何访问只能部分访问的Rails变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,我是Ruby on Rails的新手.我对大局感到非常困惑,因此,您的帮助将不胜感激.

Sorry I'm a newbie to Ruby on Rails. I'm very confused about the big picture, so your help would be appreciated.

在我的application.html.haml中,我称为= yield,该文件的输出来自rank.html.haml.现在,后者可以访问rails变量@featured_image.

In my application.html.haml, I call =yield, which takes its output from ranked.html.haml. Now, the latter has access to the rails variable @featured_image.

我要做的是在页面加载时获取此rails变量@featured_image,以便在此之后可以预加载该图像和带有ID的图像.

What I want to do is to get hold of this rails variable @featured_image on page load, so that I can preload that image and images with ids right after that.

但是我的application.html.haml中的window.onload = function()无法访问@featured_image ...

But my window.onload = function() in application.html.haml has no access to @featured_image...

我该怎么做?

谢谢!

推荐答案

正如Chris Heald所述,@ featured_image变量是控制器上的实例变量,您可以在视图中访问它.要从javascript中使用它,您基本上要做的就是将其写到您的布局中,或部分地写在这样的脚本块中的某个位置(这是erb,而不是haml):

As Chris Heald noted, the @featured_image variable is an instance variable on the controller, and you have access to it in your views. To use it from javascript, what you'll basically have to do is write it into your layout or partial somewhere in a script block like this (this is erb, not haml):

<script>
  var featured_image="<%= @featured_image %>";
</script>

很显然,您需要在@featured_image中添加nil值检查并以适合您的应用的方式处理它,否则请确保始终将其设置为某些值.克里斯的建议是使用助手,这也是一个很好的建议,但是我不确定该助手对于新手需要做什么.

Obviously, you'll want to add in a check for nil value in @featured_image and handle it in a way that's appropriate for your app, or otherwise ensure that its always set to something. Chris's suggestion to use a helper is also a good one but I wasn't sure it was obvious what the helper would need to do for a newbie.

这篇关于如何访问只能部分访问的Rails变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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