简体   繁体   中英

How to render partial view?

I have the following:

/controllers/test_controller.rb

/views/test/index.html.erb

/views/test/_partial.html.erb

I want to render the partial in the index view. I'm doing this:

index.html.erb

<h1>Test#index</h1>
<%= render "_partial" %>

_partial.html.erb

<p>This is partial content</p>

When I go to localhost:3000/test/index, I get this error:

ActionView::MissingTemplate in Test#index
Missing partial /__partial with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.
Extracted source (around line #2):

1 <h1>Test#index</h1>
2 <%= render "_partial" %>

Any idea what I'm doing wrong?

This question has already been answered, but when the partial is in the same directory as your current view, you can just render the partial with no underscore. But if you want to extract a partial from another controller you will need to take it one step back and use a more complete path, like "users/partial" .

All depends where is your partial. If you have the partial _partial in layouts folder, you only have to do is call the partial like this <%= render "partial" %> .

Rails know that a file with the underscore at the beggining is a partial. So, when you render the partial, you don't have to use the underscore.

Remember, Rails is convention over configuration.

You can try this

<% @users.each do |user| %>
        <%= render 'erb_partials/post', user: user %>
    <% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM