geekelo / dsa_practice

This repo is maintained just for the purpose of daily data structures and algorithm practice and proficiency
1 stars 0 forks source link

How should you use content_for and yield? #27

Open geekelo opened 1 month ago

geekelo commented 1 month ago

In Ruby on Rails, content_for and yield are used together to manage content sections in layouts and views. They are commonly used to insert dynamic content into specific sections of a layout or view from the corresponding templates. Here's how you can use content_for and yield effectively:

  1. Define Content Sections in Layouts: In your layout file (usually located in app/views/layouts/ directory), define sections where dynamic content can be inserted using yield. For example:

    <!DOCTYPE html>
    <html>
    <head>
     <title>My App</title>
    </head>
    <body>
     <header>
       <!-- Header content -->
     </header>
    
     <div class="main-content">
       <%= yield %>
     </div>
    
     <footer>
       <!-- Footer content -->
     </footer>
    </body>
    </html>
  2. Insert Content into Sections from Views: In your views, use content_for to populate specific sections defined in the layout. For example, in a view file:

    <% content_for :title, "Home Page" %>
    
    <h1>Welcome to My App</h1>
    <p>This is the home page content.</p>

    In this example, content_for :title will set the page title to "Home Page" when rendered inside the layout's <title> tag.

  3. Render Content in Layouts: When the view is rendered within the layout, the content defined with content_for is inserted into the corresponding yield section. In the layout, yield indicates where the content from the view will be inserted.

  4. Multiple Content Blocks: You can define and render multiple content blocks in a layout using yield with unique symbols and content_for with corresponding symbols in views.

    <% content_for :sidebar do %>
     <!-- Sidebar content -->
    <% end %>
    <% content_for :sidebar do %>
     <!-- Another sidebar content -->
    <% end %>

    In the layout:

    <div class="sidebar">
     <%= yield :sidebar %>
    </div>

    This allows you to insert different content into different sections of the layout from various views.

content_for and yield provide a flexible way to manage layouts and insert dynamic content into specific sections, making your views more modular and reusable. They are commonly used in Rails applications to maintain consistent layouts while allowing for customization in individual views.