将局部变量从控制器传递给视图 [英] Passing local variables to a view from controller
问题描述
由于某种原因,我无法将局部变量传递给显示视图...
I am not able for some reason to pass local variables to the show view...
在我的控制器中,我只是:
In my controller i have simply:
def show
render template: "books/show", :resource => "Some text"
end
在我看来,我会打印以下内容:
In my view i print the following:
<h1>My local variable text: <%= resource %></h1>
我收到以下消息:
undefined local variable or method `resource' for #<#<Class:0x00000118ebce90>:0x00000118ec3498>
我在控制器中尝试了以下语法:
I've tried the following syntaxes in the controller:
render template: "books/show", locals: { resource: "Some text" }
render template: "books/show", locals: { resource => "Some text" }
render template: "books/show", :locals => { resource: "Some text" }
render template: "books/show", :locals => { resource => "Some text" }
没有运气...
任何线索?
谢谢!
推荐答案
将数据从控制器传递到视图
这是一个NovelController类,将放入 app / controllers / novel_controller.rb。
class NovelController < ApplicationController
def index
@title = 'Shattered View: A Novel on Rails'
end
end
由于这是Novel控制器和索引操作,因此相应的视图位于 app / views / novel / index.html.erb $ c $中c>
Since this is the Novel controller and the index action, the corresponding view is in app/views/novel/index.html.erb
<h1><%= @title %></h1>
输出:
Shattered View: A Novel on Rails
视图在 NovelController#index
运行后被解释。这是视图可以访问和不能访问的视图:
The view is interpreted after NovelController#index
is run. Here's what the view can and can't access:
- 它可以访问实例变量
@title
,因为它们是在NovelController#index
完成运行时在NovelController
对象上定义的。 - 它可以调用实例变量
@title
的实例方法。
- It can access the instance variables
@title
, because they've been defined on theNovelController
object by the timeNovelController#index
finishes running. - It can call instance methods of the instance variables
@title
.
这篇关于将局部变量从控制器传递给视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!