本文簡要介紹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類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。