Câu hỏi phỏng vấn Ruby on Rails
Câu hỏi

What is the difference betw...

Câu trả lời

In Ruby on Rails, content_for and yield are both used to manage and insert content into layouts, but they serve different purposes and have distinct behaviors.

yield

  • Purpose: yield is used to insert content from a view into a layout. It acts as a placeholder where the content of the view will be rendered.
  • Usage: The simplest form of yield is to insert the entire content of a view into a layout. For example:
    html Copy
    <html>
      <head></head>
      <body>
        <%= yield %>
      </body>
    </html>
    This will render the entire content of the view into the body of the layout.
  • Named Yields: You can also have multiple named yield blocks in a layout to insert content into specific sections:
    html Copy
    <html>
      <head>
        <%= yield :head %>
      </head>
      <body>
        <%= yield %>
      </body>
    </html>
    Here, yield :head will insert content specifically designated for the :head section[1][4].

content_for

  • Purpose: content_for is used to capture content in a view and store it in a named block, which can then be rendered in a layout or another view.
  • Usage: You define a block of content in a view using content_for and give it a name:
    erb Copy
    <% content_for :head do %>
      <title>A simple page</title>
    <% end %>
    <p>Hello, Rails!</p>
    This content can then be rendered in the layout using yield with the same name:
    html Copy
    <html>
      <head>
        <%= yield :head %>
      </head>
      <body>
        <%= yield %>
      </body>
    </html>
    The result will be:
    html Copy
    <html>
      <head>
        <title>A simple page</title>
      </head>
      <body>
        <p>Hello, Rails!</p>
      </body>
    </html>
  • Flexibility: content_for can be used in helper modules and can store content for later use, which yield cannot do. This...
senior

senior

Gợi ý câu hỏi phỏng vấn

junior

Mention what is the role of Rails Controller?

expert

What is a Rails engine?

entry

Explain what is rake in Rails?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào