Search code examples
ruby-on-railsrubycontrollers

How can I change the titles of multiple pages with the controller?


I have 4 html layout like below. . this is say is fix.html.erb

!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example Test</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>

Now I want to know If is there any way that I can change the title with the help of controllers? We can create an application layout and put the common codes there, but then that title will get applied to all the pages.


Solution

  • Try:

    # Layout (needs to be *.html.erb, not plain .html)
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title><%= yield :title %></title>
      </head>
      <body>
        <%= yield %>
      </body>
    </html>
    
    # View
    
    <% provide(:title, 'My title') %>
    <h1>Hello</h1>