From: Philip Mak Date: 2002-11-09T17:47:21+09:00 Subject: An alternative HTML generation syntax I'm using Ruby to output HTML a lot these days. I know of these methods: 1. Use CGI::Html4. Problem: Must use '+' all the time to join things. If I forget a '+', everything in the block before the '+' will get silently ignored since only the return value matters. 2. Manually using puts or print statements. I get tired of having to type 'puts' all the time. 3. Use eruby. Problem: Can't seem to use this inside methods. I'm trying to come up with another method of HTML generation that minimizes typing and is readable. Here's an example. Instead of this piece of code: puts "

" puts "NEW!" if flag == 'new' puts "UPDATED!" if flag == 'updated' puts "
" if numparts > 1 puts "Parts:" (1..numparts).each do |i| puts %Q{ [#{i}]} end end puts "by #{author.display}" if author puts "

" It would be this: HTML.new { p { t 'NEW!' if flag == 'new' t 'UPDATED!' if flag == 'updated' br if numparts > 1 t 'Parts:' (1..numparts).each do |i| a(:href => "#{i}.asp") { "[#{i}]" } end end } } The HTML class would be something like this: class HTML def initialize(&block) @buff = '' self.instance_eval &block puts @buff end def p @buff += "

#{yield || @buff}

" end # define a, h1, h2, etc. and all the other HTML tags similarly end Whenever an HTML function (like "p" or "a") is called, it will generate some HTML code and tack it onto a buffer. Finally at the end, the contents of the buffer are returned. Any thoughts on this? Do you like the interface to my HTML class (can it be made any easier)? Are there any other HTML-generation-with-Ruby methods that I missed?