package require quill 1.0 namespace import ::quill::*template name arglist ?initbody? template
% template greeting {name} {Hello, $name!} ::greeting % greeting World Hello, World! %The template shown is equivalent to this Tcl proc:
proc greeting {name} { return [tsubst {Hello, $name}] }Or, since a proc automatically returns the value of the last command executed in its body, we could simplify it as so:
proc greeting {name} { tsubst {Hello, $name} }Either way, the template version is simpler and more expressive, especially as the template string gets larger.
Sometimes a template requires some initialization of variables or other processing that can't conveniently be done in the template string itself. Consequently, template allows the caller to define an "initialization" body. This is just a block of Tcl code that's called just before the template is expanded. It usually defines variables that are then substituted into the template.
Suppose, for example, a template argument should be converted to upper case. Compare
template greeting {name} {Hello, [string toupper $name]}with
template greeting {name} { set name [string toupper $name] } {Hello, $name!}The second separates the data processing from the template string, and so is clearer.
It's normal when using templates to indent the template string according to the logic of the code. This sometimes results in extra whitespace at the beginning of each line. If this is troublesome, the the whitespace can be removed by the caller, or the |<-- marker can be used to mark the left margin:
% template greeting {name} { |<-- Hello, $name! How are you? } ::greeting % greeting World Hello, World! How are you? %The |<-- must be the first token in the template string; the vertical bar indicates the left margin of the template. All whitespace to the left of that will be removed automatically. Processing of |<-- is done by the tsubst command, so |<-- can be used at the beginning of both template and tsubst strings.
If the initbody is specified, it contains Tcl code to be executed before the template is expanded. Normally, the only variables which will be in scope when the template string is expanded are the template command's arguments; the initbody is usually used to initialize other variables for inclusion in the template.
See tsubst for information on how tsubst differs from the standard Tcl subst command.
If the first non-whitespace token in template is |<-- (a vertical bar, followed by a left angle bracket, followed by two hyphens), then the vertical bar marks the left margin of the template string. All whitespace to the left of the vertical bar will be deleted before the substitution is done. The line on which the |<-- appears will also be deleted, along with any blank lines which precede it.