【问题标题】:Rails 3: Two different layouts with the same controller and action?Rails 3:具有相同控制器和动作的两种不同布局?
【发布时间】:2011-12-29 06:16:35
【问题描述】:

假设您想要一个具有两种不同布局的博客。一种布局应该看起来像带有页眉、页脚、菜单等的传统博客。另一个布局应该只包含博客文章,仅此而已。在不丢失与模型的连接、仅强制执行和呈现一个动作并防止重复自己 (DRY) 的情况下,您将如何做到这一点?

posts_controller.rb

class PostsController < ApplicationController
  layout :choose_layout

  # chooses the layout by action name
  # problem: it forces us to use more than one action
  def choose_layout
    if action_name == 'diashow'
      return 'diashow'
    else
      return 'application'
    end
  end

  # the one and only action
  def index
    @posts = Post.all
    @number_posts = Post.count
    @timer_sec = 5

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

  # the unwanted action
  # it should execute and render the index action
  def diashow
    index # no sense cuz of no index-view rendering
    #render :action => "index" # doesn't get the model information
  end

  [..]
end

可能我想走错路,但找不到正确的路。

更新:

我的解决方案如下所示:

posts_controller.rb

class PostsController < ApplicationController
  layout :choose_layout

  def choose_layout
    current_uri = request.env['PATH_INFO']
    if current_uri.include?('diashow')
      return 'diashow'
    else
      return 'application'
    end
  end

  def index
    @posts = Post.all
    @number_posts = Post.count
    @timer_sec = 5

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

  [..]
end

config/routes.rb

Wpr::Application.routes.draw do
  root :to => 'posts#index'

  match 'diashow' => 'posts#index'

  [..]
end

两条不同的路线指向同一个位置(控制器/动作)。 current_uri = request.env['PATH_INFO'] 将 url 保存到一个变量中,下面的 if current_uri.include?('diashow') 检查它是否是我们在 routes.rb 中配置的路由。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 layout controller action


    【解决方案1】:

    您将根据特定条件选择要呈现的布局。例如,URL 中的参数、正在呈现页面的设备等。

    只需在 choose_layout 函数中使用该条件,而不是根据 action_name 决定布局。 diashow 操作是不必要的。

    【讨论】:

    • 谢谢!我得到了另一个条件,没有这个不愉快的diashowaction。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2011-04-08
    • 2014-10-07
    • 2020-05-05
    相关资源
    最近更新 更多