1 # = ERB -- Ruby Templating
3 # Author:: Masatoshi SEKI
4 # Documentation:: James Edward Gray II and Gavin Sinclair
6 # See ERB for primary documentation and ERB::Util for a couple of utility
9 # Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
11 # You can redistribute it and/or modify it under the same terms as Ruby.
14 # = ERB -- Ruby Templating
18 # ERB provides an easy to use but powerful templating system for Ruby. Using
19 # ERB, actual Ruby code can be added to any plain text document for the
20 # purposes of generating document information details and/or flow control.
22 # A very simple example is this:
27 # template = ERB.new <<-EOF
28 # The value of x is: <%= x %>
30 # puts template.result(binding)
32 # <em>Prints:</em> The value of x is: 42
34 # More complex examples are given below.
39 # ERB recognizes certain tags in the provided template and converts them based
42 # <% Ruby code -- inline with output %>
43 # <%= Ruby expression -- replace with result %>
44 # <%# comment -- ignored -- useful in testing %>
45 # % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
46 # %% replaced with % if first thing on a line and % processing is used
47 # <%% or %%> -- replace with <% or %> respectively
49 # All other text is passed through ERB filtering unchanged.
54 # There are several settings you can change when you use ERB:
55 # * the nature of the tags that are recognized;
56 # * the value of <tt>$SAFE</tt> under which the template is run;
57 # * the binding used to resolve local variables in the template.
59 # See the ERB.new and ERB#result methods for more detail.
66 # ERB is useful for any generic templating situation. Note that in this example, we use the
67 # convenient "% at start of line" tag, and we quote the template literally with
68 # <tt>%q{...}</tt> to avoid trouble with the backslash.
74 # From: James Edward Gray II <james@grayproductions.net>
76 # Subject: Addressing Needs
80 # Just wanted to send a quick note assuring that your needs are being
83 # I want you to know that my team will keep working on the issues,
86 # <%# ignore numerous minor requests -- focus on priorities %>
87 # % priorities.each do |priority|
91 # Thanks for your patience.
93 # James Edward Gray II
96 # message = ERB.new(template, 0, "%<>")
98 # # Set up template data.
99 # to = "Community Spokesman <spokesman@ruby_community.org>"
100 # priorities = [ "Run Ruby Quiz",
101 # "Document Modules",
102 # "Answer Questions on Ruby Talk" ]
105 # email = message.result
110 # From: James Edward Gray II <james@grayproductions.net>
111 # To: Community Spokesman <spokesman@ruby_community.org>
112 # Subject: Addressing Needs
116 # Just wanted to send a quick note assuring that your needs are being addressed.
118 # I want you to know that my team will keep working on the issues, especially:
122 # * Answer Questions on Ruby Talk
124 # Thanks for your patience.
126 # James Edward Gray II
130 # ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in
131 # this example to provide a special binding when the template is run, so that the instance
132 # variables in the Product object can be resolved.
136 # # Build template data class.
138 # def initialize( code, name, desc, cost )
147 # def add_feature( feature )
148 # @features << feature
151 # # Support templating of member data.
162 # <head><title>Ruby Toys -- <%= @name %></title></head>
165 # <h1><%= @name %> (<%= @code %>)</h1>
166 # <p><%= @desc %></p>
169 # <% @features.each do |f| %>
170 # <li><b><%= f %></b></li>
175 # <% if @cost < 10 %>
176 # <b>Only <%= @cost %>!!!</b>
178 # Call for a price, today!
186 # rhtml = ERB.new(template)
188 # # Set up template data.
189 # toy = Product.new( "TZ-1002",
191 # "Geek's Best Friend! Responds to Ruby commands...",
193 # toy.add_feature("Listens for verbal commands in the Ruby language!")
194 # toy.add_feature("Ignores Perl, Java, and all C variants.")
195 # toy.add_feature("Karate-Chop Action!!!")
196 # toy.add_feature("Matz signature on left leg.")
197 # toy.add_feature("Gem studded eyes... Rubies, of course!")
200 # rhtml.run(toy.get_binding)
202 # <i>Generates (some blank lines removed):</i>
205 # <head><title>Ruby Toys -- Rubysapien</title></head>
208 # <h1>Rubysapien (TZ-1002)</h1>
209 # <p>Geek's Best Friend! Responds to Ruby commands...</p>
212 # <li><b>Listens for verbal commands in the Ruby language!</b></li>
213 # <li><b>Ignores Perl, Java, and all C variants.</b></li>
214 # <li><b>Karate-Chop Action!!!</b></li>
215 # <li><b>Matz signature on left leg.</b></li>
216 # <li><b>Gem studded eyes... Rubies, of course!</b></li>
220 # Call for a price, today!
229 # There are a variety of templating solutions available in various Ruby projects:
230 # * ERB's big brother, eRuby, works the same but is written in C for speed;
231 # * Amrita (smart at producing HTML/XML);
232 # * cs/Template (written in C for speed);
233 # * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
234 # * and others; search the RAA.
236 # Rails, the web application framework, uses ERB to create views.
239 Revision = '$Date:: $' #'
241 # Returns revision information for the erb.rb module.
243 "erb.rb [2.0.4 #{ERB::Revision.split[1]}]"
250 class Compiler # :nodoc:
251 class PercentLine # :nodoc:
259 class Scanner # :nodoc:
260 SplitRegexp = /(<%%)|(%%>)|(<%=)|(<%#)|(<%)|(%>)|(\n)/
263 def self.regist_scanner(klass, trim_mode, percent)
264 @scanner_map[[trim_mode, percent]] = klass
267 def self.default_scanner=(klass)
268 @default_scanner = klass
271 def self.make_scanner(src, trim_mode, percent)
272 klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
273 klass.new(src, trim_mode, percent)
276 def initialize(src, trim_mode, percent)
285 class TrimScanner < Scanner # :nodoc:
286 TrimSplitRegexp = /(<%%)|(%%>)|(<%=)|(<%#)|(<%)|(%>\n)|(%>)|(\n)/
288 def initialize(src, trim_mode, percent)
290 @trim_mode = trim_mode
293 @scan_line = self.method(:trim_line1)
294 elsif @trim_mode == '<>'
295 @scan_line = self.method(:trim_line2)
296 elsif @trim_mode == '-'
297 @scan_line = self.method(:explicit_trim_line)
299 @scan_line = self.method(:scan_line)
307 @src.each_line do |line|
308 percent_line(line, &block)
311 @src.each_line do |line|
312 @scan_line.call(line, &block)
318 def percent_line(line, &block)
319 if @stag || line[0] != ?%
320 return @scan_line.call(line, &block)
325 @scan_line.call(line, &block)
327 yield(PercentLine.new(line.chomp))
332 line.split(SplitRegexp).each do |token|
339 line.split(TrimSplitRegexp).each do |token|
352 line.split(TrimSplitRegexp).each do |token|
354 head = token unless head
357 if is_erb_stag?(head)
368 ExplicitTrimRegexp = /(^[ \t]*<%-)|(-%>\n?\z)|(<%-)|(-%>)|(<%%)|(%%>)|(<%=)|(<%#)|(<%)|(%>)|(\n)/
369 def explicit_trim_line(line)
370 line.split(ExplicitTrimRegexp).each do |token|
372 if @stag.nil? && /[ \t]*<%-/ =~ token
374 elsif @stag && /-%>\n/ =~ token
377 elsif @stag && token == '-%>'
385 ERB_STAG = %w(<%= <%# <%)
391 Scanner.default_scanner = TrimScanner
393 class SimpleScanner < Scanner # :nodoc:
395 @src.each_line do |line|
396 line.split(SplitRegexp).each do |token|
404 Scanner.regist_scanner(SimpleScanner, nil, false)
408 class SimpleScanner2 < Scanner # :nodoc:
410 stag_reg = /(.*?)(<%%|<%=|<%#|<%|\n|\z)/
411 etag_reg = /(.*?)(%%>|%>|\n|\z)/
412 scanner = StringScanner.new(@src)
414 scanner.scan(@stag ? etag_reg : stag_reg)
417 yield(text) unless text.empty?
418 yield(elem) unless elem.empty?
422 Scanner.regist_scanner(SimpleScanner2, nil, false)
424 class PercentScanner < Scanner # :nodoc:
427 stag_reg = /(.*?)(<%%|<%=|<%#|<%|\n|\z)/
428 etag_reg = /(.*?)(%%>|%>|\n|\z)/
429 scanner = StringScanner.new(@src)
431 if new_line && @stag.nil?
432 if scanner.scan(/%%/)
436 elsif scanner.scan(/%/)
437 yield(PercentLine.new(scanner.scan(/.*?(\n|\z)/).chomp))
441 scanner.scan(@stag ? etag_reg : stag_reg)
444 yield(text) unless text.empty?
445 yield(elem) unless elem.empty?
446 new_line = (elem == "\n")
450 Scanner.regist_scanner(PercentScanner, nil, true)
452 class ExplicitScanner < Scanner # :nodoc:
455 stag_reg = /(.*?)(<%%|<%=|<%#|<%-|<%|\n|\z)/
456 etag_reg = /(.*?)(%%>|-%>|%>|\n|\z)/
457 scanner = StringScanner.new(@src)
459 if new_line && @stag.nil? && scanner.scan(/[ \t]*<%-/)
464 scanner.scan(@stag ? etag_reg : stag_reg)
467 new_line = (elem == "\n")
468 yield(text) unless text.empty?
471 if scanner.scan(/(\n|\z)/)
478 yield(elem) unless elem.empty?
483 Scanner.regist_scanner(ExplicitScanner, '-', false)
488 class Buffer # :nodoc:
489 def initialize(compiler, enc=nil)
492 @script = enc ? "#coding:#{enc.to_s}\n" : ""
493 @compiler.pre_cmd.each do |x|
504 @script << (@line.join('; '))
511 @compiler.post_cmd.each do |x|
514 @script << (@line.join('; '))
520 out = Buffer.new(self, s.encoding)
523 scanner = make_scanner(s.dup.force_encoding("ASCII-8BIT"))
524 scanner.scan do |token|
528 out.push("#{@put_cmd} #{content.dump}") if content.size > 0
534 when '<%', '<%=', '<%#'
536 out.push("#{@put_cmd} #{content.dump}") if content.size > 0
540 out.push("#{@put_cmd} #{content.dump}")
553 if content[-1] == ?\n
561 out.push("#{@insert_cmd}((#{content}).to_s)")
563 # out.push("# #{content.dump}")
574 out.push("#{@put_cmd} #{content.dump}") if content.size > 0
579 def prepare_trim_mode(mode)
588 perc = mode.include?('%')
589 if mode.include?('-')
591 elsif mode.include?('<>')
593 elsif mode.include?('>')
603 def make_scanner(src)
604 Scanner.make_scanner(src, @trim_mode, @percent)
607 def initialize(trim_mode)
608 @percent, @trim_mode = prepare_trim_mode(trim_mode)
610 @insert_cmd = @put_cmd
614 attr_reader :percent, :trim_mode
615 attr_accessor :put_cmd, :insert_cmd, :pre_cmd, :post_cmd
623 # Constructs a new ERB object with the template specified in _str_.
625 # An ERB object works by building a chunk of Ruby code that will output
626 # the completed template when run. If _safe_level_ is set to a non-nil value,
627 # ERB code will be run in a separate thread with <b>$SAFE</b> set to the
630 # If _trim_mode_ is passed a String containing one or more of the following
631 # modifiers, ERB will adjust its code generation as listed:
633 # % enables Ruby code processing for lines beginning with %
634 # <> omit newline for lines starting with <% and ending in %>
635 # > omit newline for lines ending in %>
637 # _eoutvar_ can be used to set the name of the variable ERB will build up
638 # its output in. This is useful when you need to run multiple ERB
639 # templates through the same binding and/or when you want to control where
640 # output ends up. Pass the name of the variable to be used inside a String.
648 # PRODUCT = { :name => "Chicken Fried Steak",
649 # :desc => "A well messages pattie, breaded and fried.",
652 # attr_reader :product, :price
654 # def initialize( product = "", price = "" )
661 # # create and run templates, filling member data variables
662 # ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
663 # <%= PRODUCT[:name] %>
664 # <%= PRODUCT[:desc] %>
666 # ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
667 # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
668 # <%= PRODUCT[:desc] %>
673 # # setup template data
674 # listings = Listings.new
677 # puts listings.product + "\n" + listings.price
681 # Chicken Fried Steak
682 # A well messages pattie, breaded and fried.
684 # Chicken Fried Steak -- 9.95
685 # A well messages pattie, breaded and fried.
687 def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
688 @safe_level = safe_level
689 compiler = ERB::Compiler.new(trim_mode)
690 set_eoutvar(compiler, eoutvar)
691 @src = compiler.compile(str)
695 # The Ruby code generated by ERB
698 # The optional _filename_ argument passed to Kernel#eval when the ERB code
700 attr_accessor :filename
703 # Can be used to set _eoutvar_ as described in ERB#new. It's probably easier
704 # to just use the constructor though, since calling this method requires the
705 # setup of an ERB _compiler_ object.
707 def set_eoutvar(compiler, eoutvar = '_erbout')
708 compiler.put_cmd = "#{eoutvar}.concat"
709 compiler.insert_cmd = "#{eoutvar}.concat"
712 cmd.push "#{eoutvar} = ''"
714 compiler.pre_cmd = cmd
719 compiler.post_cmd = cmd
722 # Generate results and print them. (see ERB#result)
723 def run(b=TOPLEVEL_BINDING)
728 # Executes the generated ERB code to produce a completed template, returning
729 # the results of that code. (See ERB#new for details on how this process can
730 # be affected by _safe_level_.)
732 # _b_ accepts a Binding or Proc object which is used to set the context of
735 def result(b=TOPLEVEL_BINDING)
739 eval(@src, b, (@filename || '(erb)'), 0)
743 return eval(@src, b, (@filename || '(erb)'), 0)
747 def def_method(mod, methodname, fname='(ERB)') # :nodoc:
748 mod.module_eval("def #{methodname}\n" + self.src + "\nend\n", fname, -1)
751 def def_module(methodname='erb') # :nodoc:
753 def_method(mod, methodname)
757 def def_class(superklass=Object, methodname='result') # :nodoc:
758 cls = Class.new(superklass)
759 def_method(cls, methodname)
767 # A utility module for conversion routines, often handy in HTML generation.
771 # A utility method for escaping HTML tag characters in _s_.
776 # puts html_escape("is a > 0 & a < 10?")
780 # is a > 0 & a < 10?
783 s.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/</, "<")
787 module_function :html_escape
790 # A utility method for encoding the String _s_ as a URL.
795 # puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
799 # Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
802 s.to_s.dup.force_encoding("ASCII-8BIT").gsub(/[^a-zA-Z0-9_\-.]/n) {
803 sprintf("%%%02X", $&.unpack("C")[0])
808 module_function :url_encode
815 module DefMethod # :nodoc:
817 def def_erb_method(methodname, erb)
818 if erb.kind_of? String
820 File.open(fname) {|f| erb = ERB.new(f.read) }
821 erb.def_method(self, methodname, fname)
823 erb.def_method(self, methodname)
826 module_function :def_erb_method