用于动态路由静态页面的Rails模板

时间:2014-08-15 23:35:26

标签: ruby-on-rails ruby templates routes

我正在让我的Rails应用程序搜索pages文件夹,并为每个文件夹创建路径并在控制器中为它们生成方法。代码很棒!但我无法使用在其中呈现的页面加载模板文件。这是我的代码:

app/controllers/pages_controller.rb

class PagesController < ApplicationController
  attr_reader :pages_list

  def initialize
    PagesController.pages_list.each {|name|
      define_singleton_method(name) {}
    }
  end

  def self.pages_list
    Dir.glob(
        Rails.root + "app/views/pages/*"
    ).select {|f|
      File.file? f
    }.map {|f|
      File.basename(f)[0..File.basename(f).index(".").to_i-1]
    }.uniq
  end
end

config/routes.rb

PagesController.pages_list.each do |page|
  get "/#{page}", to: "pages##{page}", as: "#{page}_page"
end

我很高兴能为我放入的任何页面使用URL帮助程序进行工作。但是模板没有显示在app/views/layouts/application.html.erb

我在 PagesController

中尝试了以下操作
include HighVoltage::StaticPage

layout :application

def initialize
  PagesController.pages_list.each {|name|
    define_singleton_method(name) {render layout: "application"}
  }
end

但这对页面没有任何作用。感谢帮助!


视图是通用锅炉板:

app/views/pages/contact.html.erb

<% content_for :title do %>Contact<% end %>
<h3>Contact info for the website</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

app/views/pages/about.html.erb

<% content_for :title do %>About<% end %>
<h3>About the website</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

2 个答案:

答案 0 :(得分:1)

这不是更简单,而不是分别为每个视图创建操作,为所有视图添加一个操作吗?

路线:

get '/:page', to: 'pages#show', as: :page

控制器:

class PagesController < ApplicationController

  def show
    render params[:page], layout: 'application'
  rescue ActionView::MissingTemplate
    raise ActionController::RoutingError, 'Not Found'
  end

end

Ant应该是它。

答案 1 :(得分:0)

事实证明,您不需要在控制器中定义每个方法来执行此操作。它的工作原理是从我的示例中删除我的初始化方法并添加布局选项。

app/controllers/pages_controller.rb

class PagesController < ApplicationController
  attr_reader :pages_list
  layout "my_custom_layout"

  def self.pages_list
    Dir.glob(
        Rails.root + "app/views/pages/*"
    ).select {|f|
      File.file? f
    }.map {|f|
      File.basename(f)[0..File.basename(f).index(".").to_i-1]
    }.uniq
  end
end

config/routes.rb

PagesController.pages_list.each do |page|
  get "/#{page}", to: "pages##{page}", as: "#{page}_page"
end

即使控制器中没有定义相同名称的方法,也会调用右视图文件。