Ruby on Rails-渲染布局 [英] Ruby on Rails - render layout

查看:69
本文介绍了Ruby on Rails-渲染布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将网站分为两个部分.一种应使用应用程序布局,另一种应使用管理员布局.在我的application.rb中,我创建了一个函数,如下所示:

I'm trying to split up a web site into two sections. One which should use the application layout and one that should use the admin layout. In my application.rb I created a function as follows:

def admin_layout
  if current_user.is_able_to('siteadmin')
    render :layout => 'admin'
  else
    render :layout => 'application'
  end
end

在控制器中可能放置了一个或另一个控制器

And in the controllers where it might be one or the other I put

before_filter :admin_layout

这在某些页面(仅是文本)上工作正常,但在其他页面上却出现经典错误:

This works fine for some pages (where its just text) but for others I get the classic error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

有人知道我想念什么吗?我应该如何正确使用渲染和布局?

Does anyone have an idea of what I'm missing? How should I properly use render and layout?

推荐答案

方法render实际上将尝试呈现内容.当您只想设置布局时,就不要调用它.

The method render will actually attempt to render content; you should not call it when all you want to do is set the layout.

Rails具有所有烘烤的模式.只需将符号传递给layout,就会调用具有该名称的方法以确定当前布局:

Rails has a pattern for all of this baked in. Simply pass a symbol to layout and the method with that name will be called in order to determine the current layout:

class MyController < ApplicationController
  layout :admin_layout

  private

  def admin_layout
    # Check if logged in, because current_user could be nil.
    if logged_in? and current_user.is_able_to('siteadmin')
      "admin"
    else
      "application"
    end
  end
end

在此处查看详细信息.

这篇关于Ruby on Rails-渲染布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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