ruby - How do I write logic into a HTML file? -


i trying populate html file few parameters:

<!doctype html>         <html>         <head>         <title>'breakdown'</title>         </head>         <body>             <h1 'breakdown'>             </h1>   #{a.each |k,v|     k.each |b|       "<h2 #{a} />"       "<ol id='resultsfor#{a}'>"       v.each |result,number|       "<li #{number} #{result} />"       end       "</ol>"     end   end}         </body>         </html>" 

and output:

        <html><head>         <title>tests breakdown</title>         </head>         <body>             <h1 'breakdown' >             </h1>          abcr11r20r33          </body></html> 

where abc corresponds r1, r2, , r3 result key , numbers 1,2,3.

i seem loose additional text in each loops. thing seem getting out of varaibles , not <h2>, <ol> or <li> tags. can tell me i'm doing wrong please?

although can try , conventional ruby inlining using #{...}, tends awkward. it's rare see done on large text documents.

the problem you're having here can't mix strings , code plain old string interpolation. need have kind of template language this, can switch between logic , text content.

using example:

"<html>#{ruby_content}</html>" 

the contents of #{...} block must complete block of ruby code. cannot interrupt or split up. if you're used php, can switch , forth, won't able here.

there other ways of expressing easier manage.

erb ships ruby , gives more flexibility:

<html><%= ruby_content %></html> 

even better haml looks this:

%html   = ruby_content 

haml might take getting used to, virtually guaranteed emit valid html documents, saving lot of time in tracking down improperly closed tags or other random errors bound crop when writing html hand.

here's rough "translation" of example haml:

!!! %html   %head     %title       breakdown   %body     %h1       breakdown     - a.each |k, v|       - k.each |b|         %h2           %ol{ :id => "resultsfor#{a}" }           - v.each |result, number|             %li               = "#{number} #{result}" 

i'm not sure you're intending stuff <h2 #{a} /> isn't valid html, or <li #{number} #{result} /> means, you'll have fix part.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -