The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Text::Template::Compact - text base template expand module

SYNOPSIS

        use utf8;
        use Encode;
        use Text::Template::Compact;

        # create instance
        my $tmpl = new Text::Template::Compact();

        # load from file
        $tmpl->loadFile('template.html','utf8') or die $tmpl->error;

        # or load from text
        $tmpl->loadText('src1','hello, ${world}!','utf8') or die $tmpl->error;

        # prepare binding parameter
        my $param = { world=>'World' };

        # set default filter that used when output parameter or expression
        $tmpl->filter_default('html');

        # set encoding that used when read non-utf8 value from parameter.
        $tmpl->param_encoding('cp932');

        # set string that used for print instead of undefined value.
        $tmpl->undef_supply('(null)');

        # print to filehandle
        $tmpl->print($param,\*STDOUT,'utf8');

        # or get string output
        print Encode::encode('utf8',$tmpl->toString($param));

DESCRIPTION

The Text::Template::Compact module is text base template expand module. This module compile control tag in source text and output it with parameter data that gived at runtime. Its main purpose is handling HTML templates in Web Application, but it also available for other situation such as mail,XML,etc,.

FEATURE

  • requires perl >= 5.8.3.

  • no extra dependency.

  • this module supports various expressions in control tags.

  • unicode support. it works correctly on 'use utf8;' situation. you can apply different character encoding for source, output, and reading non-utf8 peremeter.

  • looks of control tags are ${...} or ${%...}

  • types of control tag are: print, if-elsif-else-end, for-end, while-end, eval, blockdefine, blockpaste.

  • escape filter support. also programmer can specify default filter for tags that fileter was abbreviated.

TEMPLATE SYNTAX

control tag

 ${ [label:] [% tagtype] tag-arg [;[label:] [% tagtype] tag-arg ...] [#filter]}
  • in text of template source, looks of control tag is ${...}.

  • if you want to write ${ as normal text , please escape it to $${ .

  • tokens in control tag are:

    **

    keyword that start with alphabet and underbar and follows alphabet,underbar,numeric.

    **

    "double quoted string" . if you want to write " in quoted string , please escape it to "".

    **

    numeric constant. (integer only. '.' is not supported)

    **

    any symbols except '}' and '"'

  • to specify escape filter, use '#filtername' in end of tags. filtername is one of raw,html,uri,nobr. if you omit filter spec in tag, default filter that specified by program as $tmpl->filter_default('html'); is applied.

  • you can write a number of control statement in a tag. each control statement is separated by ';' .

  • type of control statement is specified as %command in head of statement ( excepts label if exists.). if you omit %command, %print is supplied.

  • you can add label: at head of control statement (before %). this is used for break and continue.

  • if line of source text contains only whitespaces control tag excepts %print, spaces and linefeed in the line is removed at compiling source.

expression

you may use expression in control statement such as print,eval,for,if to reference data in parameter object. supported operator and literarls are:

almost same as perl:

() ++ -- ** ! ~ unary+ unary- * / % + - << >> int defined length < > <= >= lt gt le ge == != <=> eq ne cmp eq ne cmp & | ^ && || // ?: = **= *= /= %= += -= <<= >>= &= |= ^= &&= ||= //= , print scalar join push pop shift unshift not and or xor

notation is changed from perl:
  • cat (same as . in perl)

  • repeat (same as x in perl)

  • makearray (same as [] in perl)

  • makehash (same as {} in perl)

other operators:
  • bool (same as not not )

  • nz (same as !=0 )

  • call coderef,args... (same as coderef->(args,...) in perl)

  • call obj,"method",args... (same as obj->"method"(args,...) in perl)

literal:
  • keyword that start with alphabet and underbar and follows alphabet,underbar,numeric.

  • "double quoted string" . if you want to write " in quoted string , please escape it to "".

  • numeric constant. (integer only. '.' is not supported)

expression for data reference

        # for example, the parameter data structure that passed to template is this:
        $VAR1 = {
                h=>{ a=>1,b=>2,c=>3, ge=>4},
                v=>['a','b','c','d'],
                ge => 4,
                ge => 4,
        }
        #then data reference and its value is:
        h.c     => means 3
        v.1     => means 'b'
        v.(1+2) => means 'd'
        h[v.1]  => means  2  
        v[h.c]  => means 'd' 
        ge      => error.  because 'ge' is operator, not keyword.
        $ge     => means 4. using $ to change interpret of keyword and operator.
        h["ge"] => means 4. using [] to avoid interpret of keyword and operator.

looks of expression for data reference are like as name , name.key , name[2].key , $name. each node that separated by . and [] indicate hash-key or array-index in parameter data structure.

a[b]

reference hash-key or array-index of a by value of b. left term must be data reference.

a.b

reference hash-key or array-index of a by keyowrd of b. left term must be data reference. if right term is keyword , use its name as key or index. if right term is not keyword, use its value as key or index. if each term is data reference , concat the data path.

$

symbol $ is reference to whole of parameter data. and you can use $keyword to avoid conflict between keyword and operator .

$$

symbol $$ is reference to whole of template object.

examples

        ${v}            # referencde parameter data by key 'v'.
        ${"v"}          # string constant. not reference parameter data.
        ${2}            # numeric constant.not reference parameter data.
        ${va[2]}        # reffernce array by numeric subscript .
        ${va[-1]}       # negative subscript to reference end of array.
        ${va[v2]}       # use value of another data as subscript index of array.
        ${vh["v2"]}     # use string constatnt  to subscript key of hash.
        ${vh.v2}        # use keyword name      in right term of '.'
        ${va.-1}        # use expression value  in right term of '.'
        ${va.(1+2)}     # use expression value  in right term of '.'
        ${vh."v2"}      # use string  constatnt in right term of '.'
        ${va.2}         # use integer constatnt in right term of '.'
        ${va.v3}        # same as 'va.0'. if left term is array,keyword of right term is interpolated in numeric context.
        ${vh.(va.2)}    # same as 'vh.va.2'. if term is data reference, each path willbe concat.
        ${$2.2}         # example of using $ in data reference
        ${$.2.2}        # example of using $ in data reference
        ${$[2].2}       # example of using $ in data reference
        ${$defined}     # keyword after $/$$ is interpolated as dara reference although its looks is operator.
        ${$"defined"}   # constant literal after $/$$ is interpolated as dara reference.
        ${$.defined }   # Error. bare 'defined' is interpolated as operator.

%print

 Syntax:
        ${ [%print] expr }
 Examples:
        ${1,2,3}
        ${client.5.address}
        ${client[loopcount].address}
        ${ "売り上げ"."合計" }
        ${user.phone||"not available"}
        ${user.mobile?"携帯ユーザ":"PCユーザ"}
        <a href="?who=${data#uri}">${data#nobr}</a>
        <textarea name="a">${body#nobr}</textarea>

Print expression to place of control tag. And you can omit part of '%print' in tag, such as ${expr}.

%eval

 Syntax:
        ${%eval expr}
 Examples:
        ${%eval name="foo",caption="bar"}

Eval expression, but not print to outout. Also you can use operator 'print' in this tag.

%evalperl

 Syntax:
        ${%evalperl "perlcode" [result [arg [arg ...]]] }

You can write perl code in "perlcode". please quote it. If you specify data reference at 'result', result of eval is stored to it. If you specify data reference at 'arg', its value willbe copied to local variable $a,$b,... brfore eval. reference of parameter object is copied to local variable $_ before eval.

%if,%elsif,%else,%end,%ifc,%elsifc

 Syntax:
        ${ [label:] %if expr } or ${ [label:] %ifc    "perlcode" [arg [arg ...]] }
                block
        ${%elsif expr }or ${%elsifc "perlcode" [arg [arg ...]] }
                block
        ${%else}
                block
        ${%end}

%for

 Syntax:
        ${ [label:] %for item in array [index] [indexstart] }
                block
        ${%end}

item must have LValue.

array must have array reference.

index can be omit, or must have LValue.

indexstart can be omit, or must have numeric value.

loops for each element of array.

in the loop, element of index are copied to item and index.

If indexstart is specified, initial value of index will be changed.

%while

 Syntax:
        ${ [label:] %while
            [init init_expr]
            [precheck precheck_expr]
            [postcheck postcheck_expr]
            [step step_expr]
            [final final_expr]
        }
                block
        ${%end}
 
 Examples:
        ${%while init i=0 precheck i<10 step i++} ${i} ${%end}
        ${%while init i=0 postcheck i<10 step i++} ${i} ${%end}
        ${%while precheck left-- } ...  ${%end}
        ${%while postcheck --left} ...  ${%end}
 
 pseudo code to explain timing of evaluate each expression 
        (init_expr);
        loop{
                if(!precheck_expr) break;
                block
        _CONTINUE:
                if(!postcheck_expr) break;
                (step_expr);
        }
        _BREAK:
        (final_expr);

%break,%continue

 Syntax:
        ${%break [label] }
        ${%continue [label] }

These tags are used to exit block.

%blockdefine,%blockpaste

 Syntax:
        ${%blockdefine blockname }
                ...
        ${%end}
        
        ${%blockpaste blockname }

AUTHOR

tateisu tateisu@gmail.com

1 POD Error

The following errors were encountered while parsing the POD:

Around line 1782:

Non-ASCII character seen before =encoding in '"売り上げ"."合計"'. Assuming UTF-8