[英]Can partials be controller-specific?
In Rails, can partials be controller-specific? 在Rails中,局部变量可以特定于控制器吗? I have a controller for creating post and a view that went with it.
我有一个用于创建帖子的控制器和一个附带的视图。 After I renamed the view (added _) to make it a partial, it no longer seems to work.
我将视图重命名(添加了_)以使其成为局部视图后,它似乎不再起作用。
Thank you in advance. 先感谢您。
Partials cannot be rendered as views. 部分内容无法呈现为视图。 Which makes perfect sense since partials are not views - they are reusable chunks of a view.
这很合理,因为局部视图不是视图-它们是视图的可重用块。
Lets say you have: 假设您有:
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
@post = Post.new
end
end
# app/views/posts/new.html.erb
<%= form_for(@post) do |f| %>
# ...
<% end %>
If you rename new.html.erb
-> _new.html.erb
Rails will no longer be able to find the view - because it no longer is a view. 如果重命名
new.html.erb
> _new.html.erb
Rails将不再能够找到视图-因为它不再是视图。
Partials are by there very nature controller-specific. 本质上,部分是特定于控制器的。 For example:
例如:
# app/views/posts/show.html.erb
<%= render partial: 'foo' %>
Will look for app/views/posts/_foo.html.erb
. 将寻找
app/views/posts/_foo.html.erb
。
# app/views/stories/show.html.erb
<%= render partial: 'foo' %>
Will look for app/views/stories/_foo.html.erb
. 将寻找
app/views/stories/_foo.html.erb
。
Thats because Rails prepends the view lookup path with app/views/controller_name
. 那是因为Rails在视图查找路径前添加了
app/views/controller_name
。
Yes. 是。 But you need to explicitly tell Rails where the view is located.
但是您需要明确告诉Rails视图所在的位置。
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
@resource = Post.new
render 'resources/new'
end
end
# app/controllers/stories_controller.rb
class StoriesController < ApplicationController
def new
@resource = Story.new
render 'resources/new'
end
end
Or you could append the view path . 或者,您可以追加视图路径 。
class ResourcesController < ApplicationController
prepend_view_path Rails.root.join('app/views/resources')
end
class PostsController < ResourcesController
def new
@resource = Post.new
# will now default to rendering `app/views/resources/new.html.erb`
end
end
Yes. 是。 But you need to tell Rails where the partial is located.
但是您需要告诉Rails部分的位置。
<%= render partial: 'shared/social_media_icons' %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.