8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

renderってなんぞや?

Posted at

Ruby on Railsでなにかしら機能を構築し、よし!いざviewに落とし込むぞ!ってなったときに、いちいちcontrollerで定義した変数や、htmlを書くのはけっこう大変。。。!

そんな問題を解決してくれるのがrenderです。

プログラミング初心者かつ映像製作をする自分にとってrenderと言われたらエフェクト書けて重くなった映像を各フレームごと処理しなめらかな映像してくれる方のrenderしか思い浮かばず、プログラミングでのrenderってなんだ?!とドツボにハマってしまいました。

ということで調べてみると・・・
"画像や画面の内容を指示するデータの集まり(数値や数式のパラメータ、描画ルールを記述したものなど)をコンピュータプログラムで処理して、具体的な画素の集合を得ること。"

つまり、わざわざviewで一度定義した変数や、テンプレートを書かず、render + そのページに表示したい数式やhtmlの場所を指定するだけで、ポンとそのviewを返してくれるわけです。

便利!

例)app/view/user/show.html.erb

qiita.rb
puts '
  ・
  ・
  ・
  <div class="span8">
 +    <%= render 'follow_form' if signed_in? %>
      <% if @user.microposts.any? %>
        <h3>Microposts (<%= @user.microposts.count %>)</h3>
 -       <ol class="microposts">
 +        <%= render @microposts %>
 +       </ol>
        <%= will_paginate @microposts %>
      <% end %>
    </div>
  ・
  ・
  ・
'

app/view/user/show_html.erbにmicropostsを投稿順に表示させたい!
となったときに、render @micropostsを使用することことで、その値(この場合は@micropostsにひもづけられているcontentとuser idなどの値)が

    に従って順番に番号付きで表示されるということです。

    便利!

    これで、すっきりとしたhtmlを書くことが出来ます。

    8
    10
    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
    8
    10

    Delete article

    Deleted articles cannot be recovered.

    Draft of this article would be also deleted.

    Are you sure you want to delete this article?