Version 0 of TemplateRecall

Updated 2008-03-17 14:19:04 by DDG

Purpose

After seeing a lot of template approaches where the template becomes more and more bloated with programming logic I rread the interesting article at www.perl.com [L1 ]. Here it is Tcl-counterpart written as an itcl-class:

 #  Created By    : Dr. Detlef Groth
 #  Created       : Mon Mar 17 13:56:04 2008
 #
 #  Description        
 #
 #  History
 #        
 package require Itcl
 itcl::class TemplateRecall {
    public variable template_path ""
    private variable TemplateText ""
    private variable Templ 
    constructor {args} {
        eval configure $args
        if {$template_path eq ""} {
            error "Option -template_path not given"
        }
        if [catch {open $template_path r} infh] {
            puts stderr "Cannot open $template_path: $infh"
            exit
        } else {
            set TemplateText [read $infh]
            close $infh
        }
        array set Templ [list]
    }
    method render {template args} {
        if {![info exists Templ($template)]} {
            foreach line [split $TemplateText "\n"] {
                if {[regexp {\[ *=+ ([^\s]+) +=+ *\]} $line -> lastTempl]} {
                    continue
                } elseif {[info exists lastTempl]} {
                    append Templ($lastTempl) "$line\n"
                }
            }
        }
        set cpTempl $Templ($template)
        set cpTempl [regsub -all {\['} $cpTempl "'''''"]
                     set cpTempl [regsub -all {']} $cpTempl "'''''"]

        foreach {var repl} $args {
            set var [regsub {^-} $var ""]
            set cpTempl [regsub -all "'{5} +$var +'{5}" $cpTempl $repl]
        }
        return $cpTempl
    }
 }
 if {0} {
 set goods [list "oxfords,Brown leather,\$85,0" \
           "hiking,All sizes,\$55,7" \
           "tennis shoes,Women's sizes,\$35,15" \
           "flip flops,Colors of the rainbow,\$7,90" ]

 TemplateRecall tr -template_path template1.html
 puts [tr render header -title MyStore -date [clock format [clock seconds]]]
 foreach good $goods {
    set attr [split $good ,]
    set q [lindex $attr 3]
    if { $q == 0} {
        set q "Out Of stock"
    } 
    puts [tr render product_row -shoe [lindex $attr 0] -details [lindex $attr 1] \
          -price [lindex $attr 2] -quantity $q]
 }    
 puts [tr render footer]



enter categories here