Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Capturing part of template in variable in RoR

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 329
    Comment on it

    Hi Friends,
    Sometimes you need to use a small part of a template at so many places and you have to write the same lines of code on separate places and you also don't want to create separate partials for that. Rails gives a solution to your problem by providing flexibility to store a part of template into a variable, that you can use anywhere in your template or page. Rails provide two helper methods for that.

    (a) capture : - It is used to extract a part of a template into a variable, and that variable can be used in place of the part of template later. Suppose you have to use the regard text so many times, then you can use capture as:

    <% @regards = capture do %>
        <p>Regards,</p>
        <p>Raghvendra Pratap Singh</p>  
        <p>Software Engineer</p>
    <% end %>
    

    Now you can use @regards anywhere in the layout or template.

    <html>
      <head>
        <title>Hi</title>
      </head>
      <body>
        <!-- Some HTML  -->
        <%= @regards %>
      </body>
    </html>
    


    (b) content_for : - It stores a block of markup in an identifier, that can be used later. By passing an identifier as an argument to yield, subsequent call can be made for the stored content. For example suppose you have a application.html file and a main.html, and you want that some js or style needs to be included in only main.html and not in the whole site. You can use this as:
    application.html

    <html>
      <head>
        <%= yield :someJs %>
      </head>
      <body>
        <!-- Some HTML  -->
        <p>Regards,</p>
        <p>Raghvendra Pratap Singh</p>  
        <p>Software Engineer</p>
      </body>
    </html>
    


    main.html

    <% content_for :someJs do %>
      <script>
        // Some Js code
      </script>
    <% end %>
    


    Hope you like my blog. For more blogs on Rails and more technlogies. Click here

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: