當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby ERB.new用法及代碼示例

本文簡要介紹ruby語言中 ERB.new 的用法。

用法

new(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout')

使用 str 中指定的模板構造一個新的 ERB 對象。

ERB 對象通過構建一段 Ruby 代碼來工作,該代碼將在運行時輸出完整的模板。

如果 trim_mode 傳遞了包含以下一個或多個修飾符的 String ,則 ERB 將調整其代碼生成,如下所示:

%  enables Ruby code processing for lines beginning with %
<> omit newline for lines starting with <% and ending in %>
>  omit newline for lines ending in %>
-  omit blank lines ending in -%>

eoutvar 可用於設置變量的名稱 ERB 將在其中構建其輸出。當您需要通過相同的綁定運行多個 ERB 模板和/或當您想要控製輸出位置時,這很有用結束。傳遞要在 String 中使用的變量的名稱。

示例

require "erb"

# build data class
class Listings
  PRODUCT = { :name => "Chicken Fried Steak",
              :desc => "A well messages pattie, breaded and fried.",
              :cost => 9.95 }

  attr_reader :product, :price

  def initialize( product = "", price = "" )
    @product = product
    @price = price
  end

  def build
    b = binding
    # create and run templates, filling member data variables
    ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), trim_mode: "", eoutvar: "@product").result b
      <%= PRODUCT[:name] %>
      <%= PRODUCT[:desc] %>
    END_PRODUCT
    ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), trim_mode: "", eoutvar: "@price").result b
      <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
      <%= PRODUCT[:desc] %>
    END_PRICE
  end
end

# setup template data
listings = Listings.new
listings.build

puts listings.product + "\n" + listings.price

Generates

Chicken Fried Steak
A well messages pattie, breaded and fried.

Chicken Fried Steak -- 9.95
A well messages pattie, breaded and fried.

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 ERB.new。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。