Class

TemplatePage

Inheritance
< Object

Cheap-n-cheerful HTML page template system. You create a template containing:

  • variable names between percent signs (%fred%)
  • blocks of repeating stuff:
      START:key
        ... stuff
      END:key
    

You feed the code a hash. For simple variables, the values are resolved directly from the hash. For blocks, the hash entry corresponding to key will be an array of hashes. The block will be generated once for each entry. Blocks can be nested arbitrarily deeply.

The template may also contain

  IF:key
    ... stuff
  ENDIF:key

stuff will only be included in the output if the corresponding key is set in the value hash.

Usage: Given a set of templates T1, T2, etc

           values = { "name" => "Dave", state => "TX" }

           t = TemplatePage.new(T1, T2, T3)
           File.open(name, "w") {|f| t.write_html_on(f, values)}
        or
           res = ''
           t.write_html_on(res, values)

Classes & Modules

Methods

Class

Visibility Signature
public new (*templates)

Instance

Visibility Signature
public expand_line (line)
public substitute_into (lines, values)
public write_html_on (op, value_hash)

Class Method Detail

new(*templates)

templates is an array of strings containing the templates. We start at the first, and substitute in subsequent ones where the string !INCLUDE! occurs. For example, we could have the overall page template containing

  <html><body>
    <h1>Master</h1>
    !INCLUDE!
  </bost></html>

and substitute subpages in to it by passing [master, sub_page]. This gives us a cheap way of framing pages

Instance Method Detail

expand_line(line)

Given an individual line, we look for %xxx% constructs and HREF:ref:name: constructs, substituting for each.

substitute_into(lines, values)

Substitute a set of key/value pairs into the given template. Keys with scalar values have them substituted directly into the page. Those with array values invoke substitute_array (below), which examples a block of the template once for each row in the array.

This routine also copes with the IF:key directive, removing chunks of the template if the corresponding key does not appear in the hash, and the START: directive, which loops its contents for each value in an array

write_html_on(op, value_hash)

Render the templates into HTML, storing the result on op using the method <<. The value_hash contains key/value pairs used to drive the substitution (as described above)