强大的ruby模版:ERB

本文介绍了一种使用Ruby语言创建并渲染产品模板的方法。通过定义一个产品类,并为其添加特性,然后利用ERB(Embedded Ruby)来生成带有产品详情的HTML页面。此模板能根据产品的不同特性动态显示相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#http://stdlib.rubyonrails.org/

require "erb"
# Build template data class.
class Product
def initialize( code, name, desc, cost )
@code = code
@name = name
@desc = desc
@cost = cost

@features = [ ]
end

def add_feature( feature )
@features << feature
end

# Support templating of member data.
def get_binding
binding
end

# ...
end

# Create template.
template = %{
<html>
<head><title>Ruby Toys -- <%= @name %></title></head>
<body>

<h1><%= @name %> (<%= @code %>)</h1>
<p><%= @desc %></p>

<ul>
<% @features.each do |f| %>
<li><b><%= f %></b></li>
<% end %>
</ul>

<p>
<% if @cost < 10 %>
<b>Only <%= @cost %>!!!</b>
<% else %>
Call for a price, today!
<% end %>
</p>

</body>
</html>
}.gsub(/^ /, '')

rhtml = ERB.new(template)

# Set up template data.
toy = Product.new( "TZ-1002",
"Rubysapien",
"Geek's Best Friend! Responds to Ruby commands...",
999.95 )
toy.add_feature("Listens for verbal commands in the Ruby language!")
toy.add_feature("Ignores Perl, Java, and all C variants.")
toy.add_feature("Karate-Chop Action!!!")
toy.add_feature("Matz signature on left leg.")
toy.add_feature("Gem studded eyes... Rubies, of course!")

# Produce result.
rhtml.run(toy.get_binding)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值