Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Builder templates in ROR and its uses

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 224
    Comment on it

    Action view templates can be written in various ways depending on the format of the response. If the response is in html format then we can use .erb files i.e. html files, with embedded ruby in it. If the format is in xml then we need to use files with .builder extension. Builder::XmlMarkup library is used for these templates.

    In templates with .xml.builder extension we use a xml object . This is an object of XmlMarkup class. Example :

    xml.a("Findnerd", "href" => "http://findnerd.com") 
    
    # => <a href="http://findnerd.com">Findnerd</a>
    

    In the above example .a is a method of the object xml. Any such method within a block of another method gives a nested xml output. Example:

    def  index
    @users = User.all
          respond_to do |format|
             format.xml {render :xml => @users}
          end
    end
    

    In the index.xml.builder file we can write like this to generate xml view:

    xml.instruct!         
    @users.each do |user|
         xml.div do
           xml.p(user.name)
           xml.p(user.email)
         end
    end
    

    Assuming there are only 2 user outputs of the above code, then it will be something like this:

    <div>
      <p>David</p>
      <p>david@gmail.com</p>
    </div>
    <div>
      <p>Joe</p>
      <p>joe@hotmail.com</p>
    </div>
    

 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: