1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
require 'tempura/template'
## Template
template_html = <<END_OF_TEMPLATE_HTML
<body>
<table border="1">
<tr><th>name</th><th>author</th></tr>
<tr _block_="items//each//item">
<td _child_="item.name">(will be replaced with a name of each item)</td>
<td _child_="item.author">(will be replaced with an author of each item)</td>
</tr>
</table>
<form method="POST" _event_="add">
name: <input type="text" name="name"/>
author: <input type="text" name="author"/>
<input type="submit" value="Add"/>
</form>
</body>
END_OF_TEMPLATE_HTML
## Model
class Item
attr_reader :name, :author
def initialize(name, author)
@name = name
@author = author
end
end
class ItemContainer
attr_reader :items
def initialize
@items = []
end
def add(name, author)
@items << Item.new(name, author)
end
end
## Real Data
data = ItemContainer.new
data.add("Ruby", "matz")
data.add("Perl", "Larry Wall")
data.add("Python", "Guido")
## Expand
tmpl = Tempura::Template.new_with_string(template_html)
tmpl.default_action = "myapp.cgi"
## Print result
puts tmpl.expand(data)
__END__
# Result
<body>
<table border='1'>
<tr><th>name</th><th>author</th></tr>
<tr>
<td>Ruby</td>
<td>matz</td>
</tr><tr>
<td>Perl</td>
<td>Larry Wall</td>
</tr><tr>
<td>Python</td>
<td>Guido</td>
</tr>
</table>
<form action='myapp.cgi' method='POST'><input name='event' type='hidden' value='add'/>
name: <input name='name' type='text'/>
author: <input name='author' type='text'/>
<input type='submit' value='Add'/>
</form>
</body>
|