0
0

More than 3 years have passed since last update.

部分テンプレート

Last updated at Posted at 2021-03-18

部分テンプレートのやり方

例えば、tweetを作ってたとすると
下のようなコードを記述したとする

app/views/tweets/index.html.erb
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー


<% @tweets.each do |tweet| %>
 < div class="content_post" style="background-image: url(<%= tweet.image %>);">
< div class="more">
< span><%= image_tag 'arrow_top.png' %>
< ul class="more_list">
< li>
<%= link_to '詳細', tweet_path(tweet.id), method: :get %>
< /li>
<% if user_signed_in? && current_user.id == tweet.user_id %>
< li>
<%= link_to '編集', edit_tweet_path(tweet.id), method: :get %>
< /li>
< li>
<%= link_to '削除', tweet_path(tweet.id), method: :delete %>
< /li>
<% end %>
< /ul>
< /div>
< p><%= tweet.text %>
< span class="name">
< a href="/users/<%= tweet.user.id %>">
< span>投稿者<%= tweet.user.nickname %>
< /a>
< /span>
< /div>
<% end %>
< /div>

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

<% @tweets.each do |tweet| %>〜<% end %>の中身を全て切り取りapp/views/tweets/_tweet.html.erbに貼り付けたとする。

app/views/tweets/index.html.erbは以下の記述で済む

< div class="contents row">
<% @tweets.each do |tweet| %>
<%= render partial: "tweet", locals: { tweet: tweet } %>
<% end %>
< /div>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0