What is the difference between render and yield in Rails

前端 未结 3 726
自闭症患者
自闭症患者 2021-02-13 11:00

Can someone explain the difference between \"<%= render %>\" and \"<%= yield %> with <% content_for :partial do %>/

3条回答
  •  我寻月下人不归
    2021-02-13 11:46

    First of all, yield is ruby, render is rails. Usually one uses a common layout for the application whose inner content changes according to action/context. The problem usually lies in defining where our layout ends and context-specific template begins. Take, for instance, the HTML title tag. Let's say you have an application called Cities. In most cases, you want your page title to be "Cities" all the time. But, if you're for instance, inside Amsterdam page, then you would like the have "Amsterdam" as your page title.

    # application.html.erb
    
      
        <%= content_for?(:page_title) ? yield(:page_title) : "Cities" %>
        ......
    
    # city/index.html.erb
    <% content_for :page_title do %>
      <%= @city.name %> 
    <% end %>
    
    

    Within Rails you usually define your application title in your application layout. One strategy for changing the page title would be to use content_for in the specific cities template and change accordingly.

    Render, on the other hand, accomplishes different rendering strategies. Straight. When you call render, it renders. content_for/yield doesn't render automatically, it is stored somewhere and then fills up the missing spots in the due places. So, you can think of it as more as a "store/search/replace" in comparison to render, which just plain renders.

    Good rule of thumb to use one over the other is: if the template you are writing needs to present different information per context, strongly consider using content_for.

提交回复
热议问题