2012-02-04 61 views
1

我在做Lynda.com的rails教程,他们解释了如何呈现另一个视图,而不是使用render('methodname')的默认视图。Rails控制器:可以嵌套渲染视图吗?

但是,我注意到这个渲染不是“嵌套”的。例如,在下面的代码中,localhost:3000/demo/index会在views/demo/hello.html.erb中生成视图,而localhost:3000/demo/hello会呈现文本'Hello there'。

有没有一种方法可以进行“嵌套”渲染,即在此示例中请求演示/索引将返回'Hello there'?

(此外,一些使用案例嵌套渲染就好了。我问只是出于好奇。)

class DemoController < ApplicationController 
    def index 
    render ('hello')    
    end 

    def hello 
    render(:text => 'Hello there') 
    end 

end 

回答

2

我不知道你到底是通过嵌套渲染的意思。

方案1

如果你想行动“指数”被触发,但模板“hello.html.erb”中显示,你可以做

def index 
    render :action => :hello 
end 

,这会使得模板app/views/demos/hello.html.erb(或其他格式,如果你想要它(即在url中指定它))。

所以render :action => :hello只是一个捷径。

您也可以做render :template => "hello.html.erb"render :file => Rails.root.join("app/views/demos/hello.html.erb")(有时有用)。

方案2

如果你想呈现的文本,你可以叫你好指数法

def index 
    hello 
end 

里面方法如果你不想从打招呼动作其他的东西,是运行你可以将它分开为其他方法,如下所示:

def render_hello 
    render :text => "Hello world" 
end 

def index 
    # some other stuff going on... 
    render_hello 
end 

def hello 
    # some other stuff going on... 
    render_hello 
end 

在同一个动作中不能渲染两次。

顺便说一句,url不应该说/demos/index,但只是/demos。 索引是resources路由(resources :demos)的默认操作。

请选择适合您的场景(以便我可以从此答案中删除不必要的文本)。

0

你当前正在尝试在控制器中渲染,所有的渲染应该在Rails中的视图中处理。

因此,对于您的结构之上,你DemoController应该

应用程序/控制器/ demo_controller.rb

位于一个文件,要呈现将在位于文件的意见:

app/views/demo/index.html。ERB

应用程序/视图/演示/ _hello.html.erb(前端下划线文件名_hello.html.erb指示Rails的,这是一个“局部”的另一个页面中被渲染)

在index.html.erb文件中,您可以调用hello.html.erb文件的渲染。最后的代码应该是这样的:

demo_controller.rb

class DemoController < ApplicationController 

    def index   
    end 

end 

index.html.erb

<%= render 'demo/hello' %> 

_hello.html.erb

<p>Hello there</p>