本文简要介绍ruby语言中 ERB类
的用法。
ERB
- Ruby 模板
介绍
ERB
为 Ruby 提供了一个易于使用但函数强大的模板系统。使用 ERB
,可以将实际的 Ruby 代码添加到任何纯文本文档中,以生成文档信息详细信息和/或流控制。
一个非常简单的例子是这样的:
require 'erb'
x = 42
template = ERB.new <<-EOF
The value of x is: <%= x %>
EOF
puts template.result(binding)
Prints:
x 的值为:42
下面给出更复杂的例子。
公认的标签
ERB
识别提供的模板中的某些标签并根据以下规则对其进行转换:
<% Ruby code -- inline with output %> <%= Ruby expression -- replace with result %> <%# comment -- ignored -- useful in testing %> (`<% #` doesn't work. Don't use Ruby comments.) % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new) %% replaced with % if first thing on a line and % processing is used <%% or %%> -- replace with <% or %> respectively
所有其他文本通过 ERB
过滤保持不变。
选项
使用 ERB 时可以更改几个设置:
-
被识别的标签的性质;
-
用于解析模板中的局部变量的绑定。
有关详细信息,请参阅 ERB.new
和 ERB#result
方法。
字符编码
ERB
(或由 ERB
生成的 Ruby 代码)返回与输入字符串具有相同字符编码的字符串。然而,当输入字符串有一个魔术注释时,它会返回一个由魔术注释指定的编码的字符串。
# -*- coding: utf-8 -*-
require 'erb'
template = ERB.new <<EOF
<%#-*- coding: Big5 -*-%>
\_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>.
EOF
puts template.result
Prints:
_ ENCODING
_ 是 Big5。
例子
纯文本
ERB
适用于任何通用模板情况。请注意,在此示例中,我们使用方便的“% at start of line”标记,并用%q{...}
逐字引用模板以避免反斜杠出现问题。
require "erb"
# Create template.
template = %q{
From: James Edward Gray II <james@grayproductions.net>
To: <%= to %>
Subject: Addressing Needs
<%= to[/\w+/] %>:
Just wanted to send a quick note assuring that your needs are being
addressed.
I want you to know that my team will keep working on the issues,
especially:
<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
* <%= priority %>
% end
Thanks for your patience.
James Edward Gray II
}.gsub(/^ /, '')
message = ERB.new(template, trim_mode: "%<>")
# Set up template data.
to = "Community Spokesman <spokesman@ruby_community.org>"
priorities = [ "Run Ruby Quiz",
"Document Modules",
"Answer Questions on Ruby Talk" ]
# Produce result.
email = message.result
puts email
Generates:
From: James Edward Gray II <james@grayproductions.net> To: Community Spokesman <spokesman@ruby_community.org> Subject: Addressing Needs Community: Just wanted to send a quick note assuring that your needs are being addressed. I want you to know that my team will keep working on the issues, especially: * Run Ruby Quiz * Document Modules * Answer Questions on Ruby Talk Thanks for your patience. James Edward Gray II
HTML 中的红 gems
ERB
经常用于.rhtml
文件(带有嵌入 Ruby 的 HTML)。请注意,此示例中需要在模板运行时提供特殊绑定,以便可以解析 Product 对象中的实例变量。
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)
Generates (some blank lines removed):
<html> <head><title>Ruby Toys -- Rubysapien</title></head> <body> <h1>Rubysapien (TZ-1002)</h1> <p>Geek's Best Friend! Responds to Ruby commands...</p> <ul> <li><b>Listens for verbal commands in the Ruby language!</b></li> <li><b>Ignores Perl, Java, and all C variants.</b></li> <li><b>Karate-Chop Action!!!</b></li> <li><b>Matz signature on left leg.</b></li> <li><b>Gem studded eyes... Rubies, of course!</b></li> </ul> <p> Call for a price, today! </p> </body> </html>
注意
各种 Ruby 项目中提供了各种模板解决方案。例如,与 Ruby 一起分发的 RDoc
使用自己的模板引擎,可以在其他地方重用。
其他流行的引擎可以在 The Ruby Toolbox 的相应 Category 中找到。
相关用法
- Ruby ERB.location=用法及代码示例
- Ruby ERBIO类用法及代码示例
- Ruby ERB.def_class用法及代码示例
- Ruby ERB.def_module用法及代码示例
- Ruby ERB.def_method用法及代码示例
- Ruby ERB.new用法及代码示例
- Ruby Enumerable.any?用法及代码示例
- Ruby Enumerable min_by()用法及代码示例
- Ruby Enumerable each_witth_object()用法及代码示例
- Ruby ErrorHighlight.spot用法及代码示例
- Ruby Enumerable.slice_before用法及代码示例
- Ruby Enumerable each_cons()用法及代码示例
- Ruby Enumerator each_with_index用法及代码示例
- Ruby Encoding.compatible?用法及代码示例
- Ruby Enumerable.uniq用法及代码示例
- Ruby Enumerator each_with_object用法及代码示例
- Ruby ENV.empty?用法及代码示例
- Ruby Enumerable uniq()用法及代码示例
- Ruby Enumerable.find_all用法及代码示例
- Ruby Enumerator.peek_values用法及代码示例
- Ruby Enumerable.max用法及代码示例
- Ruby Enumerable.map用法及代码示例
- Ruby Enumerable min()用法及代码示例
- Ruby Enumerable.min_by用法及代码示例
- Ruby Enumerable.find_index用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 ERB类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。