开发者

Passing parameters to Rails 3 template in generator

In Rails 2 generators, it's possible to pass data to the template in the following manner:

record.template(
  "src.html.erb",
  "dest.html.erb",
  :assigns => { :id => id, :name => name }

In Rails 3, it looks like template is the new method. Unfortunately, it looks like the third parameter, confi开发者_如何转开发g, only accepts a :verbose option. Attempting to pass values via :assigns doesn't seem to work.

Does anyone know how I can pass dynamic value to my Rails 3 template?


Example of passing parameters to views in Rails 3.

https://github.com/rails/rails/blob/master/railties/lib/rails/generators/erb/controller/controller_generator.rb

# ...
actions.each do |action|
  @action = action
  @path = File.join(base_path, filename_with_extensions(action))
  template filename_with_extensions(:view), @path
end

Template:

https://github.com/rails/rails/blob/master/railties/lib/rails/generators/erb/controller/templates/view.html.erb

<h1><%= class_name %>#<%= @action %></h1>
<p>Find me in <%= @path %></p>


Rails 3 templates have access to any methods within the generator, so in your above case, if your generator had a method name and a method id, you wouldn't have to change anything in your template. Check out the RailsCast for creating generators in Rails 3 at http://railscasts.com/episodes/218-making-generators-in-rails-3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜