Template.pm 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  1. # -*- perl -*-
  2. # Text::Template.pm
  3. #
  4. # Fill in `templates'
  5. #
  6. # Copyright 2013 M. J. Dominus.
  7. # You may copy and distribute this program under the
  8. # same terms as Perl iteself.
  9. # If in doubt, write to mjd-perl-template+@plover.com for a license.
  10. #
  11. # Version 1.46
  12. package Text::Template;
  13. require 5.004;
  14. use Exporter;
  15. @ISA = qw(Exporter);
  16. @EXPORT_OK = qw(fill_in_file fill_in_string TTerror);
  17. use vars '$ERROR';
  18. use strict;
  19. $Text::Template::VERSION = '1.46';
  20. my %GLOBAL_PREPEND = ('Text::Template' => '');
  21. sub Version {
  22. $Text::Template::VERSION;
  23. }
  24. sub _param {
  25. my $kk;
  26. my ($k, %h) = @_;
  27. for $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") {
  28. return $h{$kk} if exists $h{$kk};
  29. }
  30. return;
  31. }
  32. sub always_prepend
  33. {
  34. my $pack = shift;
  35. my $old = $GLOBAL_PREPEND{$pack};
  36. $GLOBAL_PREPEND{$pack} = shift;
  37. $old;
  38. }
  39. {
  40. my %LEGAL_TYPE;
  41. BEGIN {
  42. %LEGAL_TYPE = map {$_=>1} qw(FILE FILEHANDLE STRING ARRAY);
  43. }
  44. sub new {
  45. my $pack = shift;
  46. my %a = @_;
  47. my $stype = uc(_param('type', %a) || "FILE");
  48. my $source = _param('source', %a);
  49. my $untaint = _param('untaint', %a);
  50. my $prepend = _param('prepend', %a);
  51. my $alt_delim = _param('delimiters', %a);
  52. my $broken = _param('broken', %a);
  53. unless (defined $source) {
  54. require Carp;
  55. Carp::croak("Usage: $ {pack}::new(TYPE => ..., SOURCE => ...)");
  56. }
  57. unless ($LEGAL_TYPE{$stype}) {
  58. require Carp;
  59. Carp::croak("Illegal value `$stype' for TYPE parameter");
  60. }
  61. my $self = {TYPE => $stype,
  62. PREPEND => $prepend,
  63. UNTAINT => $untaint,
  64. BROKEN => $broken,
  65. (defined $alt_delim ? (DELIM => $alt_delim) : ()),
  66. };
  67. # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken
  68. # are tainted, all the others become tainted too as a result of
  69. # sharing the expression with them. We install $source separately
  70. # to prevent it from acquiring a spurious taint.
  71. $self->{SOURCE} = $source;
  72. bless $self => $pack;
  73. return unless $self->_acquire_data;
  74. $self;
  75. }
  76. }
  77. # Convert template objects of various types to type STRING,
  78. # in which the template data is embedded in the object itself.
  79. sub _acquire_data {
  80. my ($self) = @_;
  81. my $type = $self->{TYPE};
  82. if ($type eq 'STRING') {
  83. # nothing necessary
  84. } elsif ($type eq 'FILE') {
  85. my $data = _load_text($self->{SOURCE});
  86. unless (defined $data) {
  87. # _load_text already set $ERROR
  88. return undef;
  89. }
  90. if ($self->{UNTAINT} && _is_clean($self->{SOURCE})) {
  91. _unconditionally_untaint($data);
  92. }
  93. $self->{TYPE} = 'STRING';
  94. $self->{FILENAME} = $self->{SOURCE};
  95. $self->{SOURCE} = $data;
  96. } elsif ($type eq 'ARRAY') {
  97. $self->{TYPE} = 'STRING';
  98. $self->{SOURCE} = join '', @{$self->{SOURCE}};
  99. } elsif ($type eq 'FILEHANDLE') {
  100. $self->{TYPE} = 'STRING';
  101. local $/;
  102. my $fh = $self->{SOURCE};
  103. my $data = <$fh>; # Extra assignment avoids bug in Solaris perl5.00[45].
  104. if ($self->{UNTAINT}) {
  105. _unconditionally_untaint($data);
  106. }
  107. $self->{SOURCE} = $data;
  108. } else {
  109. # This should have been caught long ago, so it represents a
  110. # drastic `can't-happen' sort of failure
  111. my $pack = ref $self;
  112. die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting";
  113. }
  114. $self->{DATA_ACQUIRED} = 1;
  115. }
  116. sub source {
  117. my ($self) = @_;
  118. $self->_acquire_data unless $self->{DATA_ACQUIRED};
  119. return $self->{SOURCE};
  120. }
  121. sub set_source_data {
  122. my ($self, $newdata) = @_;
  123. $self->{SOURCE} = $newdata;
  124. $self->{DATA_ACQUIRED} = 1;
  125. $self->{TYPE} = 'STRING';
  126. 1;
  127. }
  128. sub compile {
  129. my $self = shift;
  130. return 1 if $self->{TYPE} eq 'PREPARSED';
  131. return undef unless $self->_acquire_data;
  132. unless ($self->{TYPE} eq 'STRING') {
  133. my $pack = ref $self;
  134. # This should have been caught long ago, so it represents a
  135. # drastic `can't-happen' sort of failure
  136. die "Can only compile $pack objects of subtype STRING, but this is $self->{TYPE}; aborting";
  137. }
  138. my @tokens;
  139. my $delim_pats = shift() || $self->{DELIM};
  140. my ($t_open, $t_close) = ('{', '}');
  141. my $DELIM; # Regex matches a delimiter if $delim_pats
  142. if (defined $delim_pats) {
  143. ($t_open, $t_close) = @$delim_pats;
  144. $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))";
  145. @tokens = split /($DELIM|\n)/, $self->{SOURCE};
  146. } else {
  147. @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self->{SOURCE};
  148. }
  149. my $state = 'TEXT';
  150. my $depth = 0;
  151. my $lineno = 1;
  152. my @content;
  153. my $cur_item = '';
  154. my $prog_start;
  155. while (@tokens) {
  156. my $t = shift @tokens;
  157. next if $t eq '';
  158. if ($t eq $t_open) { # Brace or other opening delimiter
  159. if ($depth == 0) {
  160. push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
  161. $cur_item = '';
  162. $state = 'PROG';
  163. $prog_start = $lineno;
  164. } else {
  165. $cur_item .= $t;
  166. }
  167. $depth++;
  168. } elsif ($t eq $t_close) { # Brace or other closing delimiter
  169. $depth--;
  170. if ($depth < 0) {
  171. $ERROR = "Unmatched close brace at line $lineno";
  172. return undef;
  173. } elsif ($depth == 0) {
  174. push @content, [$state, $cur_item, $prog_start] if $cur_item ne '';
  175. $state = 'TEXT';
  176. $cur_item = '';
  177. } else {
  178. $cur_item .= $t;
  179. }
  180. } elsif (!$delim_pats && $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\}
  181. $cur_item .= '\\';
  182. } elsif (!$delim_pats && $t =~ /^\\([{}])$/) { # Escaped (literal) brace?
  183. $cur_item .= $1;
  184. } elsif ($t eq "\n") { # Newline
  185. $lineno++;
  186. $cur_item .= $t;
  187. } else { # Anything else
  188. $cur_item .= $t;
  189. }
  190. }
  191. if ($state eq 'PROG') {
  192. $ERROR = "End of data inside program text that began at line $prog_start";
  193. return undef;
  194. } elsif ($state eq 'TEXT') {
  195. push @content, [$state, $cur_item, $lineno] if $cur_item ne '';
  196. } else {
  197. die "Can't happen error #1";
  198. }
  199. $self->{TYPE} = 'PREPARSED';
  200. $self->{SOURCE} = \@content;
  201. 1;
  202. }
  203. sub prepend_text {
  204. my ($self) = @_;
  205. my $t = $self->{PREPEND};
  206. unless (defined $t) {
  207. $t = $GLOBAL_PREPEND{ref $self};
  208. unless (defined $t) {
  209. $t = $GLOBAL_PREPEND{'Text::Template'};
  210. }
  211. }
  212. $self->{PREPEND} = $_[1] if $#_ >= 1;
  213. return $t;
  214. }
  215. sub fill_in {
  216. my $fi_self = shift;
  217. my %fi_a = @_;
  218. unless ($fi_self->{TYPE} eq 'PREPARSED') {
  219. my $delims = _param('delimiters', %fi_a);
  220. my @delim_arg = (defined $delims ? ($delims) : ());
  221. $fi_self->compile(@delim_arg)
  222. or return undef;
  223. }
  224. my $fi_varhash = _param('hash', %fi_a);
  225. my $fi_package = _param('package', %fi_a) ;
  226. my $fi_broken =
  227. _param('broken', %fi_a) || $fi_self->{BROKEN} || \&_default_broken;
  228. my $fi_broken_arg = _param('broken_arg', %fi_a) || [];
  229. my $fi_safe = _param('safe', %fi_a);
  230. my $fi_ofh = _param('output', %fi_a);
  231. my $fi_eval_package;
  232. my $fi_scrub_package = 0;
  233. my $fi_filename = _param('filename') || $fi_self->{FILENAME} || 'template';
  234. my $fi_prepend = _param('prepend', %fi_a);
  235. unless (defined $fi_prepend) {
  236. $fi_prepend = $fi_self->prepend_text;
  237. }
  238. if (defined $fi_safe) {
  239. $fi_eval_package = 'main';
  240. } elsif (defined $fi_package) {
  241. $fi_eval_package = $fi_package;
  242. } elsif (defined $fi_varhash) {
  243. $fi_eval_package = _gensym();
  244. $fi_scrub_package = 1;
  245. } else {
  246. $fi_eval_package = caller;
  247. }
  248. my $fi_install_package;
  249. if (defined $fi_varhash) {
  250. if (defined $fi_package) {
  251. $fi_install_package = $fi_package;
  252. } elsif (defined $fi_safe) {
  253. $fi_install_package = $fi_safe->root;
  254. } else {
  255. $fi_install_package = $fi_eval_package; # The gensymmed one
  256. }
  257. _install_hash($fi_varhash => $fi_install_package);
  258. }
  259. if (defined $fi_package && defined $fi_safe) {
  260. no strict 'refs';
  261. # Big fat magic here: Fix it so that the user-specified package
  262. # is the default one available in the safe compartment.
  263. *{$fi_safe->root . '::'} = \%{$fi_package . '::'}; # LOD
  264. }
  265. my $fi_r = '';
  266. my $fi_item;
  267. foreach $fi_item (@{$fi_self->{SOURCE}}) {
  268. my ($fi_type, $fi_text, $fi_lineno) = @$fi_item;
  269. if ($fi_type eq 'TEXT') {
  270. $fi_self->append_text_to_output(
  271. text => $fi_text,
  272. handle => $fi_ofh,
  273. out => \$fi_r,
  274. type => $fi_type,
  275. );
  276. } elsif ($fi_type eq 'PROG') {
  277. no strict;
  278. my $fi_lcomment = "#line $fi_lineno $fi_filename";
  279. my $fi_progtext =
  280. "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;";
  281. my $fi_res;
  282. my $fi_eval_err = '';
  283. if ($fi_safe) {
  284. $fi_safe->reval(q{undef $OUT});
  285. $fi_res = $fi_safe->reval($fi_progtext);
  286. $fi_eval_err = $@;
  287. my $OUT = $fi_safe->reval('$OUT');
  288. $fi_res = $OUT if defined $OUT;
  289. } else {
  290. my $OUT;
  291. $fi_res = eval $fi_progtext;
  292. $fi_eval_err = $@;
  293. $fi_res = $OUT if defined $OUT;
  294. }
  295. # If the value of the filled-in text really was undef,
  296. # change it to an explicit empty string to avoid undefined
  297. # value warnings later.
  298. $fi_res = '' unless defined $fi_res;
  299. if ($fi_eval_err) {
  300. $fi_res = $fi_broken->(text => $fi_text,
  301. error => $fi_eval_err,
  302. lineno => $fi_lineno,
  303. arg => $fi_broken_arg,
  304. );
  305. if (defined $fi_res) {
  306. $fi_self->append_text_to_output(
  307. text => $fi_res,
  308. handle => $fi_ofh,
  309. out => \$fi_r,
  310. type => $fi_type,
  311. );
  312. } else {
  313. return $fi_res; # Undefined means abort processing
  314. }
  315. } else {
  316. $fi_self->append_text_to_output(
  317. text => $fi_res,
  318. handle => $fi_ofh,
  319. out => \$fi_r,
  320. type => $fi_type,
  321. );
  322. }
  323. } else {
  324. die "Can't happen error #2";
  325. }
  326. }
  327. _scrubpkg($fi_eval_package) if $fi_scrub_package;
  328. defined $fi_ofh ? 1 : $fi_r;
  329. }
  330. sub append_text_to_output {
  331. my ($self, %arg) = @_;
  332. if (defined $arg{handle}) {
  333. print { $arg{handle} } $arg{text};
  334. } else {
  335. ${ $arg{out} } .= $arg{text};
  336. }
  337. return;
  338. }
  339. sub fill_this_in {
  340. my $pack = shift;
  341. my $text = shift;
  342. my $templ = $pack->new(TYPE => 'STRING', SOURCE => $text, @_)
  343. or return undef;
  344. $templ->compile or return undef;
  345. my $result = $templ->fill_in(@_);
  346. $result;
  347. }
  348. sub fill_in_string {
  349. my $string = shift;
  350. my $package = _param('package', @_);
  351. push @_, 'package' => scalar(caller) unless defined $package;
  352. Text::Template->fill_this_in($string, @_);
  353. }
  354. sub fill_in_file {
  355. my $fn = shift;
  356. my $templ = Text::Template->new(TYPE => 'FILE', SOURCE => $fn, @_)
  357. or return undef;
  358. $templ->compile or return undef;
  359. my $text = $templ->fill_in(@_);
  360. $text;
  361. }
  362. sub _default_broken {
  363. my %a = @_;
  364. my $prog_text = $a{text};
  365. my $err = $a{error};
  366. my $lineno = $a{lineno};
  367. chomp $err;
  368. # $err =~ s/\s+at .*//s;
  369. "Program fragment delivered error ``$err''";
  370. }
  371. sub _load_text {
  372. my $fn = shift;
  373. local *F;
  374. unless (open F, $fn) {
  375. $ERROR = "Couldn't open file $fn: $!";
  376. return undef;
  377. }
  378. local $/;
  379. <F>;
  380. }
  381. sub _is_clean {
  382. my $z;
  383. eval { ($z = join('', @_)), eval '#' . substr($z,0,0); 1 } # LOD
  384. }
  385. sub _unconditionally_untaint {
  386. for (@_) {
  387. ($_) = /(.*)/s;
  388. }
  389. }
  390. {
  391. my $seqno = 0;
  392. sub _gensym {
  393. __PACKAGE__ . '::GEN' . $seqno++;
  394. }
  395. sub _scrubpkg {
  396. my $s = shift;
  397. $s =~ s/^Text::Template:://;
  398. no strict 'refs';
  399. my $hash = $Text::Template::{$s."::"};
  400. foreach my $key (keys %$hash) {
  401. undef $hash->{$key};
  402. }
  403. }
  404. }
  405. # Given a hashful of variables (or a list of such hashes)
  406. # install the variables into the specified package,
  407. # overwriting whatever variables were there before.
  408. sub _install_hash {
  409. my $hashlist = shift;
  410. my $dest = shift;
  411. if (UNIVERSAL::isa($hashlist, 'HASH')) {
  412. $hashlist = [$hashlist];
  413. }
  414. my $hash;
  415. foreach $hash (@$hashlist) {
  416. my $name;
  417. foreach $name (keys %$hash) {
  418. my $val = $hash->{$name};
  419. no strict 'refs';
  420. local *SYM = *{"$ {dest}::$name"};
  421. if (! defined $val) {
  422. delete ${"$ {dest}::"}{$name};
  423. } elsif (ref $val) {
  424. *SYM = $val;
  425. } else {
  426. *SYM = \$val;
  427. }
  428. }
  429. }
  430. }
  431. sub TTerror { $ERROR }
  432. 1;
  433. =head1 NAME
  434. Text::Template - Expand template text with embedded Perl
  435. =head1 VERSION
  436. This file documents C<Text::Template> version B<1.46>
  437. =head1 SYNOPSIS
  438. use Text::Template;
  439. $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl');
  440. $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] );
  441. $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh );
  442. $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' );
  443. $template = Text::Template->new(PREPEND => q{use strict;}, ...);
  444. # Use a different template file syntax:
  445. $template = Text::Template->new(DELIMITERS => [$open, $close], ...);
  446. $recipient = 'King';
  447. $text = $template->fill_in(); # Replaces `{$recipient}' with `King'
  448. print $text;
  449. $T::recipient = 'Josh';
  450. $text = $template->fill_in(PACKAGE => T);
  451. # Pass many variables explicitly
  452. $hash = { recipient => 'Abed-Nego',
  453. friends => [ 'me', 'you' ],
  454. enemies => { loathsome => 'Bill Gates',
  455. fearsome => 'Larry Ellison' },
  456. };
  457. $text = $template->fill_in(HASH => $hash, ...);
  458. # $recipient is Abed-Nego,
  459. # @friends is ( 'me', 'you' ),
  460. # %enemies is ( loathsome => ..., fearsome => ... )
  461. # Call &callback in case of programming errors in template
  462. $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...);
  463. # Evaluate program fragments in Safe compartment with restricted permissions
  464. $text = $template->fill_in(SAFE => $compartment, ...);
  465. # Print result text instead of returning it
  466. $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...);
  467. # Parse template with different template file syntax:
  468. $text = $template->fill_in(DELIMITERS => [$open, $close], ...);
  469. # Note that this is *faster* than using the default delimiters
  470. # Prepend specified perl code to each fragment before evaluating:
  471. $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...);
  472. use Text::Template 'fill_in_string';
  473. $text = fill_in_string( <<EOM, PACKAGE => 'T', ...);
  474. Dear {$recipient},
  475. Pay me at once.
  476. Love,
  477. G.V.
  478. EOM
  479. use Text::Template 'fill_in_file';
  480. $text = fill_in_file($filename, ...);
  481. # All templates will always have `use strict vars' attached to all fragments
  482. Text::Template->always_prepend(q{use strict 'vars';});
  483. =head1 DESCRIPTION
  484. This is a library for generating form letters, building HTML pages, or
  485. filling in templates generally. A `template' is a piece of text that
  486. has little Perl programs embedded in it here and there. When you
  487. `fill in' a template, you evaluate the little programs and replace
  488. them with their values.
  489. You can store a template in a file outside your program. People can
  490. modify the template without modifying the program. You can separate
  491. the formatting details from the main code, and put the formatting
  492. parts of the program into the template. That prevents code bloat and
  493. encourages functional separation.
  494. =head2 Example
  495. Here's an example of a template, which we'll suppose is stored in the
  496. file C<formletter.tmpl>:
  497. Dear {$title} {$lastname},
  498. It has come to our attention that you are delinquent in your
  499. {$monthname[$last_paid_month]} payment. Please remit
  500. ${sprintf("%.2f", $amount)} immediately, or your patellae may
  501. be needlessly endangered.
  502. Love,
  503. Mark "Vizopteryx" Dominus
  504. The result of filling in this template is a string, which might look
  505. something like this:
  506. Dear Mr. Gates,
  507. It has come to our attention that you are delinquent in your
  508. February payment. Please remit
  509. $392.12 immediately, or your patellae may
  510. be needlessly endangered.
  511. Love,
  512. Mark "Vizopteryx" Dominus
  513. Here is a complete program that transforms the example
  514. template into the example result, and prints it out:
  515. use Text::Template;
  516. my $template = Text::Template->new(SOURCE => 'formletter.tmpl')
  517. or die "Couldn't construct template: $Text::Template::ERROR";
  518. my @monthname = qw(January February March April May June
  519. July August September October November December);
  520. my %vars = (title => 'Mr.',
  521. firstname => 'Bill',
  522. lastname => 'Gates',
  523. last_paid_month => 1, # February
  524. amount => 392.12,
  525. monthname => \@monthname,
  526. );
  527. my $result = $template->fill_in(HASH => \%vars);
  528. if (defined $result) { print $result }
  529. else { die "Couldn't fill in template: $Text::Template::ERROR" }
  530. =head2 Philosophy
  531. When people make a template module like this one, they almost always
  532. start by inventing a special syntax for substitutions. For example,
  533. they build it so that a string like C<%%VAR%%> is replaced with the
  534. value of C<$VAR>. Then they realize the need extra formatting, so
  535. they put in some special syntax for formatting. Then they need a
  536. loop, so they invent a loop syntax. Pretty soon they have a new
  537. little template language.
  538. This approach has two problems: First, their little language is
  539. crippled. If you need to do something the author hasn't thought of,
  540. you lose. Second: Who wants to learn another language? You already
  541. know Perl, so why not use it?
  542. C<Text::Template> templates are programmed in I<Perl>. You embed Perl
  543. code in your template, with C<{> at the beginning and C<}> at the end.
  544. If you want a variable interpolated, you write it the way you would in
  545. Perl. If you need to make a loop, you can use any of the Perl loop
  546. constructions. All the Perl built-in functions are available.
  547. =head1 Details
  548. =head2 Template Parsing
  549. The C<Text::Template> module scans the template source. An open brace
  550. C<{> begins a program fragment, which continues until the matching
  551. close brace C<}>. When the template is filled in, the program
  552. fragments are evaluated, and each one is replaced with the resulting
  553. value to yield the text that is returned.
  554. A backslash C<\> in front of a brace (or another backslash that is in
  555. front of a brace) escapes its special meaning. The result of filling
  556. out this template:
  557. \{ The sum of 1 and 2 is {1+2} \}
  558. is
  559. { The sum of 1 and 2 is 3 }
  560. If you have an unmatched brace, C<Text::Template> will return a
  561. failure code and a warning about where the problem is. Backslashes
  562. that do not precede a brace are passed through unchanged. If you have
  563. a template like this:
  564. { "String that ends in a newline.\n" }
  565. The backslash inside the string is passed through to Perl unchanged,
  566. so the C<\n> really does turn into a newline. See the note at the end
  567. for details about the way backslashes work. Backslash processing is
  568. I<not> done when you specify alternative delimiters with the
  569. C<DELIMITERS> option. (See L<"Alternative Delimiters">, below.)
  570. Each program fragment should be a sequence of Perl statements, which
  571. are evaluated the usual way. The result of the last statement
  572. executed will be evaluted in scalar context; the result of this
  573. statement is a string, which is interpolated into the template in
  574. place of the program fragment itself.
  575. The fragments are evaluated in order, and side effects from earlier
  576. fragments will persist into later fragments:
  577. {$x = @things; ''}The Lord High Chamberlain has gotten {$x}
  578. things for me this year.
  579. { $diff = $x - 17;
  580. $more = 'more'
  581. if ($diff == 0) {
  582. $diff = 'no';
  583. } elsif ($diff < 0) {
  584. $more = 'fewer';
  585. }
  586. '';
  587. }
  588. That is {$diff} {$more} than he gave me last year.
  589. The value of C<$x> set in the first line will persist into the next
  590. fragment that begins on the third line, and the values of C<$diff> and
  591. C<$more> set in the second fragment will persist and be interpolated
  592. into the last line. The output will look something like this:
  593. The Lord High Chamberlain has gotten 42
  594. things for me this year.
  595. That is 25 more than he gave me last year.
  596. That is all the syntax there is.
  597. =head2 The C<$OUT> variable
  598. There is one special trick you can play in a template. Here is the
  599. motivation for it: Suppose you are going to pass an array, C<@items>,
  600. into the template, and you want the template to generate a bulleted
  601. list with a header, like this:
  602. Here is a list of the things I have got for you since 1907:
  603. * Ivory
  604. * Apes
  605. * Peacocks
  606. * ...
  607. One way to do it is with a template like this:
  608. Here is a list of the things I have got for you since 1907:
  609. { my $blist = '';
  610. foreach $i (@items) {
  611. $blist .= qq{ * $i\n};
  612. }
  613. $blist;
  614. }
  615. Here we construct the list in a variable called C<$blist>, which we
  616. return at the end. This is a little cumbersome. There is a shortcut.
  617. Inside of templates, there is a special variable called C<$OUT>.
  618. Anything you append to this variable will appear in the output of the
  619. template. Also, if you use C<$OUT> in a program fragment, the normal
  620. behavior, of replacing the fragment with its return value, is
  621. disabled; instead the fragment is replaced with the value of C<$OUT>.
  622. This means that you can write the template above like this:
  623. Here is a list of the things I have got for you since 1907:
  624. { foreach $i (@items) {
  625. $OUT .= " * $i\n";
  626. }
  627. }
  628. C<$OUT> is reinitialized to the empty string at the start of each
  629. program fragment. It is private to C<Text::Template>, so
  630. you can't use a variable named C<$OUT> in your template without
  631. invoking the special behavior.
  632. =head2 General Remarks
  633. All C<Text::Template> functions return C<undef> on failure, and set the
  634. variable C<$Text::Template::ERROR> to contain an explanation of what
  635. went wrong. For example, if you try to create a template from a file
  636. that does not exist, C<$Text::Template::ERROR> will contain something like:
  637. Couldn't open file xyz.tmpl: No such file or directory
  638. =head2 C<new>
  639. $template = new Text::Template ( TYPE => ..., SOURCE => ... );
  640. This creates and returns a new template object. C<new> returns
  641. C<undef> and sets C<$Text::Template::ERROR> if it can't create the
  642. template object. C<SOURCE> says where the template source code will
  643. come from. C<TYPE> says what kind of object the source is.
  644. The most common type of source is a file:
  645. new Text::Template ( TYPE => 'FILE', SOURCE => $filename );
  646. This reads the template from the specified file. The filename is
  647. opened with the Perl C<open> command, so it can be a pipe or anything
  648. else that makes sense with C<open>.
  649. The C<TYPE> can also be C<STRING>, in which case the C<SOURCE> should
  650. be a string:
  651. new Text::Template ( TYPE => 'STRING',
  652. SOURCE => "This is the actual template!" );
  653. The C<TYPE> can be C<ARRAY>, in which case the source should be a
  654. reference to an array of strings. The concatenation of these strings
  655. is the template:
  656. new Text::Template ( TYPE => 'ARRAY',
  657. SOURCE => [ "This is ", "the actual",
  658. " template!",
  659. ]
  660. );
  661. The C<TYPE> can be FILEHANDLE, in which case the source should be an
  662. open filehandle (such as you got from the C<FileHandle> or C<IO::*>
  663. packages, or a glob, or a reference to a glob). In this case
  664. C<Text::Template> will read the text from the filehandle up to
  665. end-of-file, and that text is the template:
  666. # Read template source code from STDIN:
  667. new Text::Template ( TYPE => 'FILEHANDLE',
  668. SOURCE => \*STDIN );
  669. If you omit the C<TYPE> attribute, it's taken to be C<FILE>.
  670. C<SOURCE> is required. If you omit it, the program will abort.
  671. The words C<TYPE> and C<SOURCE> can be spelled any of the following ways:
  672. TYPE SOURCE
  673. Type Source
  674. type source
  675. -TYPE -SOURCE
  676. -Type -Source
  677. -type -source
  678. Pick a style you like and stick with it.
  679. =over 4
  680. =item C<DELIMITERS>
  681. You may also add a C<DELIMITERS> option. If this option is present,
  682. its value should be a reference to an array of two strings. The first
  683. string is the string that signals the beginning of each program
  684. fragment, and the second string is the string that signals the end of
  685. each program fragment. See L<"Alternative Delimiters">, below.
  686. =item C<UNTAINT>
  687. If your program is running in taint mode, you may have problems if
  688. your templates are stored in files. Data read from files is
  689. considered 'untrustworthy', and taint mode will not allow you to
  690. evaluate the Perl code in the file. (It is afraid that a malicious
  691. person might have tampered with the file.)
  692. In some environments, however, local files are trustworthy. You can
  693. tell C<Text::Template> that a certain file is trustworthy by supplying
  694. C<UNTAINT =E<gt> 1> in the call to C<new>. This will tell
  695. C<Text::Template> to disable taint checks on template code that has
  696. come from a file, as long as the filename itself is considered
  697. trustworthy. It will also disable taint checks on template code that
  698. comes from a filehandle. When used with C<TYPE =E<gt> 'string'> or C<TYPE
  699. =E<gt> 'array'>, it has no effect.
  700. See L<perlsec> for more complete information about tainting.
  701. Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr
  702. for help with this feature.
  703. =item C<PREPEND>
  704. This option is passed along to the C<fill_in> call unless it is
  705. overridden in the arguments to C<fill_in>. See L<C<PREPEND> feature
  706. and using C<strict> in templates> below.
  707. =item C<BROKEN>
  708. This option is passed along to the C<fill_in> call unless it is
  709. overridden in the arguments to C<fill_in>. See L<C<BROKEN>> below.
  710. =back
  711. =head2 C<compile>
  712. $template->compile()
  713. Loads all the template text from the template's source, parses and
  714. compiles it. If successful, returns true; otherwise returns false and
  715. sets C<$Text::Template::ERROR>. If the template is already compiled,
  716. it returns true and does nothing.
  717. You don't usually need to invoke this function, because C<fill_in>
  718. (see below) compiles the template if it isn't compiled already.
  719. If there is an argument to this function, it must be a reference to an
  720. array containing alternative delimiter strings. See C<"Alternative
  721. Delimiters">, below.
  722. =head2 C<fill_in>
  723. $template->fill_in(OPTIONS);
  724. Fills in a template. Returns the resulting text if successful.
  725. Otherwise, returns C<undef> and sets C<$Text::Template::ERROR>.
  726. The I<OPTIONS> are a hash, or a list of key-value pairs. You can
  727. write the key names in any of the six usual styles as above; this
  728. means that where this manual says C<PACKAGE> (for example) you can
  729. actually use any of
  730. PACKAGE Package package -PACKAGE -Package -package
  731. Pick a style you like and stick with it. The all-lowercase versions
  732. may yield spurious warnings about
  733. Ambiguous use of package => resolved to "package"
  734. so you might like to avoid them and use the capitalized versions.
  735. At present, there are eight legal options: C<PACKAGE>, C<BROKEN>,
  736. C<BROKEN_ARG>, C<SAFE>, C<HASH>, C<OUTPUT>, and C<DELIMITERS>.
  737. =over 4
  738. =item C<PACKAGE>
  739. C<PACKAGE> specifies the name of a package in which the program
  740. fragments should be evaluated. The default is to use the package from
  741. which C<fill_in> was called. For example, consider this template:
  742. The value of the variable x is {$x}.
  743. If you use C<$template-E<gt>fill_in(PACKAGE =E<gt> 'R')> , then the C<$x> in
  744. the template is actually replaced with the value of C<$R::x>. If you
  745. omit the C<PACKAGE> option, C<$x> will be replaced with the value of
  746. the C<$x> variable in the package that actually called C<fill_in>.
  747. You should almost always use C<PACKAGE>. If you don't, and your
  748. template makes changes to variables, those changes will be propagated
  749. back into the main program. Evaluating the template in a private
  750. package helps prevent this. The template can still modify variables
  751. in your program if it wants to, but it will have to do so explicitly.
  752. See the section at the end on `Security'.
  753. Here's an example of using C<PACKAGE>:
  754. Your Royal Highness,
  755. Enclosed please find a list of things I have gotten
  756. for you since 1907:
  757. { foreach $item (@items) {
  758. $item_no++;
  759. $OUT .= " $item_no. \u$item\n";
  760. }
  761. }
  762. Signed,
  763. Lord High Chamberlain
  764. We want to pass in an array which will be assigned to the array
  765. C<@items>. Here's how to do that:
  766. @items = ('ivory', 'apes', 'peacocks', );
  767. $template->fill_in();
  768. This is not very safe. The reason this isn't as safe is that if you
  769. had a variable named C<$item_no> in scope in your program at the point
  770. you called C<fill_in>, its value would be clobbered by the act of
  771. filling out the template. The problem is the same as if you had
  772. written a subroutine that used those variables in the same way that
  773. the template does. (C<$OUT> is special in templates and is always
  774. safe.)
  775. One solution to this is to make the C<$item_no> variable private to the
  776. template by declaring it with C<my>. If the template does this, you
  777. are safe.
  778. But if you use the C<PACKAGE> option, you will probably be safe even
  779. if the template does I<not> declare its variables with C<my>:
  780. @Q::items = ('ivory', 'apes', 'peacocks', );
  781. $template->fill_in(PACKAGE => 'Q');
  782. In this case the template will clobber the variable C<$Q::item_no>,
  783. which is not related to the one your program was using.
  784. Templates cannot affect variables in the main program that are
  785. declared with C<my>, unless you give the template references to those
  786. variables.
  787. =item C<HASH>
  788. You may not want to put the template variables into a package.
  789. Packages can be hard to manage: You can't copy them, for example.
  790. C<HASH> provides an alternative.
  791. The value for C<HASH> should be a reference to a hash that maps
  792. variable names to values. For example,
  793. $template->fill_in(HASH => { recipient => "The King",
  794. items => ['gold', 'frankincense', 'myrrh'],
  795. object => \$self,
  796. });
  797. will fill out the template and use C<"The King"> as the value of
  798. C<$recipient> and the list of items as the value of C<@items>. Note
  799. that we pass an array reference, but inside the template it appears as
  800. an array. In general, anything other than a simple string or number
  801. should be passed by reference.
  802. We also want to pass an object, which is in C<$self>; note that we
  803. pass a reference to the object, C<\$self> instead. Since we've passed
  804. a reference to a scalar, inside the template the object appears as
  805. C<$object>.
  806. The full details of how it works are a little involved, so you might
  807. want to skip to the next section.
  808. Suppose the key in the hash is I<key> and the value is I<value>.
  809. =over 4
  810. =item *
  811. If the I<value> is C<undef>, then any variables named C<$key>,
  812. C<@key>, C<%key>, etc., are undefined.
  813. =item *
  814. If the I<value> is a string or a number, then C<$key> is set to that
  815. value in the template.
  816. =item *
  817. For anything else, you must pass a reference.
  818. If the I<value> is a reference to an array, then C<@key> is set to
  819. that array. If the I<value> is a reference to a hash, then C<%key> is
  820. set to that hash. Similarly if I<value> is any other kind of
  821. reference. This means that
  822. var => "foo"
  823. and
  824. var => \"foo"
  825. have almost exactly the same effect. (The difference is that in the
  826. former case, the value is copied, and in the latter case it is
  827. aliased.)
  828. =item *
  829. In particular, if you want the template to get an object or any kind,
  830. you must pass a reference to it:
  831. $template->fill_in(HASH => { database_handle => \$dbh, ... });
  832. If you do this, the template will have a variable C<$database_handle>
  833. which is the database handle object. If you leave out the C<\>, the
  834. template will have a hash C<%database_handle>, which exposes the
  835. internal structure of the database handle object; you don't want that.
  836. =back
  837. Normally, the way this works is by allocating a private package,
  838. loading all the variables into the package, and then filling out the
  839. template as if you had specified that package. A new package is
  840. allocated each time. However, if you I<also> use the C<PACKAGE>
  841. option, C<Text::Template> loads the variables into the package you
  842. specified, and they stay there after the call returns. Subsequent
  843. calls to C<fill_in> that use the same package will pick up the values
  844. you loaded in.
  845. If the argument of C<HASH> is a reference to an array instead of a
  846. reference to a hash, then the array should contain a list of hashes
  847. whose contents are loaded into the template package one after the
  848. other. You can use this feature if you want to combine several sets
  849. of variables. For example, one set of variables might be the defaults
  850. for a fill-in form, and the second set might be the user inputs, which
  851. override the defaults when they are present:
  852. $template->fill_in(HASH => [\%defaults, \%user_input]);
  853. You can also use this to set two variables with the same name:
  854. $template->fill_in(HASH => [{ v => "The King" },
  855. { v => [1,2,3] },
  856. ]
  857. );
  858. This sets C<$v> to C<"The King"> and C<@v> to C<(1,2,3)>.
  859. =item C<BROKEN>
  860. If any of the program fragments fails to compile or aborts for any
  861. reason, and you have set the C<BROKEN> option to a function reference,
  862. C<Text::Template> will invoke the function. This function is called
  863. the I<C<BROKEN> function>. The C<BROKEN> function will tell
  864. C<Text::Template> what to do next.
  865. If the C<BROKEN> function returns C<undef>, C<Text::Template> will
  866. immediately abort processing the template and return the text that it
  867. has accumulated so far. If your function does this, it should set a
  868. flag that you can examine after C<fill_in> returns so that you can
  869. tell whether there was a premature return or not.
  870. If the C<BROKEN> function returns any other value, that value will be
  871. interpolated into the template as if that value had been the return
  872. value of the program fragment to begin with. For example, if the
  873. C<BROKEN> function returns an error string, the error string will be
  874. interpolated into the output of the template in place of the program
  875. fragment that cased the error.
  876. If you don't specify a C<BROKEN> function, C<Text::Template> supplies
  877. a default one that returns something like
  878. Program fragment delivered error ``Illegal division by 0 at
  879. template line 37''
  880. (Note that the format of this message has changed slightly since
  881. version 1.31.) The return value of the C<BROKEN> function is
  882. interpolated into the template at the place the error occurred, so
  883. that this template:
  884. (3+4)*5 = { 3+4)*5 }
  885. yields this result:
  886. (3+4)*5 = Program fragment delivered error ``syntax error at template line 1''
  887. If you specify a value for the C<BROKEN> attribute, it should be a
  888. reference to a function that C<fill_in> can call instead of the
  889. default function.
  890. C<fill_in> will pass a hash to the C<broken> function.
  891. The hash will have at least these three members:
  892. =over 4
  893. =item C<text>
  894. The source code of the program fragment that failed
  895. =item C<error>
  896. The text of the error message (C<$@>) generated by eval.
  897. The text has been modified to omit the trailing newline and to include
  898. the name of the template file (if there was one). The line number
  899. counts from the beginning of the template, not from the beginning of
  900. the failed program fragment.
  901. =item C<lineno>
  902. The line number of the template at which the program fragment began.
  903. =back
  904. There may also be an C<arg> member. See C<BROKEN_ARG>, below
  905. =item C<BROKEN_ARG>
  906. If you supply the C<BROKEN_ARG> option to C<fill_in>, the value of the
  907. option is passed to the C<BROKEN> function whenever it is called. The
  908. default C<BROKEN> function ignores the C<BROKEN_ARG>, but you can
  909. write a custom C<BROKEN> function that uses the C<BROKEN_ARG> to get
  910. more information about what went wrong.
  911. The C<BROKEN> function could also use the C<BROKEN_ARG> as a reference
  912. to store an error message or some other information that it wants to
  913. communicate back to the caller. For example:
  914. $error = '';
  915. sub my_broken {
  916. my %args = @_;
  917. my $err_ref = $args{arg};
  918. ...
  919. $$err_ref = "Some error message";
  920. return undef;
  921. }
  922. $template->fill_in(BROKEN => \&my_broken,
  923. BROKEN_ARG => \$error,
  924. );
  925. if ($error) {
  926. die "It didn't work: $error";
  927. }
  928. If one of the program fragments in the template fails, it will call
  929. the C<BROKEN> function, C<my_broken>, and pass it the C<BROKEN_ARG>,
  930. which is a reference to C<$error>. C<my_broken> can store an error
  931. message into C<$error> this way. Then the function that called
  932. C<fill_in> can see if C<my_broken> has left an error message for it
  933. to find, and proceed accordingly.
  934. =item C<SAFE>
  935. If you give C<fill_in> a C<SAFE> option, its value should be a safe
  936. compartment object from the C<Safe> package. All evaluation of
  937. program fragments will be performed in this compartment. See L<Safe>
  938. for full details about such compartments and how to restrict the
  939. operations that can be performed in them.
  940. If you use the C<PACKAGE> option with C<SAFE>, the package you specify
  941. will be placed into the safe compartment and evaluation will take
  942. place in that package as usual.
  943. If not, C<SAFE> operation is a little different from the default.
  944. Usually, if you don't specify a package, evaluation of program
  945. fragments occurs in the package from which the template was invoked.
  946. But in C<SAFE> mode the evaluation occurs inside the safe compartment
  947. and cannot affect the calling package. Normally, if you use C<HASH>
  948. without C<PACKAGE>, the hash variables are imported into a private,
  949. one-use-only package. But if you use C<HASH> and C<SAFE> together
  950. without C<PACKAGE>, the hash variables will just be loaded into the
  951. root namespace of the C<Safe> compartment.
  952. =item C<OUTPUT>
  953. If your template is going to generate a lot of text that you are just
  954. going to print out again anyway, you can save memory by having
  955. C<Text::Template> print out the text as it is generated instead of
  956. making it into a big string and returning the string. If you supply
  957. the C<OUTPUT> option to C<fill_in>, the value should be a filehandle.
  958. The generated text will be printed to this filehandle as it is
  959. constructed. For example:
  960. $template->fill_in(OUTPUT => \*STDOUT, ...);
  961. fills in the C<$template> as usual, but the results are immediately
  962. printed to STDOUT. This may result in the output appearing more
  963. quickly than it would have otherwise.
  964. If you use C<OUTPUT>, the return value from C<fill_in> is still true on
  965. success and false on failure, but the complete text is not returned to
  966. the caller.
  967. =item C<PREPEND>
  968. You can have some Perl code prepended automatically to the beginning
  969. of every program fragment. See L<C<PREPEND> feature and using
  970. C<strict> in templates> below.
  971. =item C<DELIMITERS>
  972. If this option is present, its value should be a reference to a list
  973. of two strings. The first string is the string that signals the
  974. beginning of each program fragment, and the second string is the
  975. string that signals the end of each program fragment. See
  976. L<"Alternative Delimiters">, below.
  977. If you specify C<DELIMITERS> in the call to C<fill_in>, they override
  978. any delimiters you set when you created the template object with
  979. C<new>.
  980. =back
  981. =head1 Convenience Functions
  982. =head2 C<fill_this_in>
  983. The basic way to fill in a template is to create a template object and
  984. then call C<fill_in> on it. This is useful if you want to fill in
  985. the same template more than once.
  986. In some programs, this can be cumbersome. C<fill_this_in> accepts a
  987. string, which contains the template, and a list of options, which are
  988. passed to C<fill_in> as above. It constructs the template object for
  989. you, fills it in as specified, and returns the results. It returns
  990. C<undef> and sets C<$Text::Template::ERROR> if it couldn't generate
  991. any results.
  992. An example:
  993. $Q::name = 'Donald';
  994. $Q::amount = 141.61;
  995. $Q::part = 'hyoid bone';
  996. $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q);
  997. Dear {$name},
  998. You owe me \\${sprintf('%.2f', $amount)}.
  999. Pay or I will break your {$part}.
  1000. Love,
  1001. Grand Vizopteryx of Irkutsk.
  1002. EOM
  1003. Notice how we included the template in-line in the program by using a
  1004. `here document' with the C<E<lt>E<lt>> notation.
  1005. C<fill_this_in> is a deprecated feature. It is only here for
  1006. backwards compatibility, and may be removed in some far-future version
  1007. in C<Text::Template>. You should use C<fill_in_string> instead. It
  1008. is described in the next section.
  1009. =head2 C<fill_in_string>
  1010. It is stupid that C<fill_this_in> is a class method. It should have
  1011. been just an imported function, so that you could omit the
  1012. C<Text::Template-E<gt>> in the example above. But I made the mistake
  1013. four years ago and it is too late to change it.
  1014. C<fill_in_string> is exactly like C<fill_this_in> except that it is
  1015. not a method and you can omit the C<Text::Template-E<gt>> and just say
  1016. print fill_in_string(<<'EOM', ...);
  1017. Dear {$name},
  1018. ...
  1019. EOM
  1020. To use C<fill_in_string>, you need to say
  1021. use Text::Template 'fill_in_string';
  1022. at the top of your program. You should probably use
  1023. C<fill_in_string> instead of C<fill_this_in>.
  1024. =head2 C<fill_in_file>
  1025. If you import C<fill_in_file>, you can say
  1026. $text = fill_in_file(filename, ...);
  1027. The C<...> are passed to C<fill_in> as above. The filename is the
  1028. name of the file that contains the template you want to fill in. It
  1029. returns the result text. or C<undef>, as usual.
  1030. If you are going to fill in the same file more than once in the same
  1031. program you should use the longer C<new> / C<fill_in> sequence instead.
  1032. It will be a lot faster because it only has to read and parse the file
  1033. once.
  1034. =head2 Including files into templates
  1035. People always ask for this. ``Why don't you have an include
  1036. function?'' they want to know. The short answer is this is Perl, and
  1037. Perl already has an include function. If you want it, you can just put
  1038. {qx{cat filename}}
  1039. into your template. VoilE<agrave>.
  1040. If you don't want to use C<cat>, you can write a little four-line
  1041. function that opens a file and dumps out its contents, and call it
  1042. from the template. I wrote one for you. In the template, you can say
  1043. {Text::Template::_load_text(filename)}
  1044. If that is too verbose, here is a trick. Suppose the template package
  1045. that you are going to be mentioning in the C<fill_in> call is package
  1046. C<Q>. Then in the main program, write
  1047. *Q::include = \&Text::Template::_load_text;
  1048. This imports the C<_load_text> function into package C<Q> with the
  1049. name C<include>. From then on, any template that you fill in with
  1050. package C<Q> can say
  1051. {include(filename)}
  1052. to insert the text from the named file at that point. If you are
  1053. using the C<HASH> option instead, just put C<include =E<gt>
  1054. \&Text::Template::_load_text> into the hash instead of importing it
  1055. explicitly.
  1056. Suppose you don't want to insert a plain text file, but rather you
  1057. want to include one template within another? Just use C<fill_in_file>
  1058. in the template itself:
  1059. {Text::Template::fill_in_file(filename)}
  1060. You can do the same importing trick if this is too much to type.
  1061. =head1 Miscellaneous
  1062. =head2 C<my> variables
  1063. People are frequently surprised when this doesn't work:
  1064. my $recipient = 'The King';
  1065. my $text = fill_in_file('formletter.tmpl');
  1066. The text C<The King> doesn't get into the form letter. Why not?
  1067. Because C<$recipient> is a C<my> variable, and the whole point of
  1068. C<my> variables is that they're private and inaccessible except in the
  1069. scope in which they're declared. The template is not part of that
  1070. scope, so the template can't see C<$recipient>.
  1071. If that's not the behavior you want, don't use C<my>. C<my> means a
  1072. private variable, and in this case you don't want the variable to be
  1073. private. Put the variables into package variables in some other
  1074. package, and use the C<PACKAGE> option to C<fill_in>:
  1075. $Q::recipient = $recipient;
  1076. my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q');
  1077. or pass the names and values in a hash with the C<HASH> option:
  1078. my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient });
  1079. =head2 Security Matters
  1080. All variables are evaluated in the package you specify with the
  1081. C<PACKAGE> option of C<fill_in>. if you use this option, and if your
  1082. templates don't do anything egregiously stupid, you won't have to
  1083. worry that evaluation of the little programs will creep out into the
  1084. rest of your program and wreck something.
  1085. Nevertheless, there's really no way (except with C<Safe>) to protect
  1086. against a template that says
  1087. { $Important::Secret::Security::Enable = 0;
  1088. # Disable security checks in this program
  1089. }
  1090. or
  1091. { $/ = "ho ho ho"; # Sabotage future uses of <FH>.
  1092. # $/ is always a global variable
  1093. }
  1094. or even
  1095. { system("rm -rf /") }
  1096. so B<don't> go filling in templates unless you're sure you know what's
  1097. in them. If you're worried, or you can't trust the person who wrote
  1098. the template, use the C<SAFE> option.
  1099. A final warning: program fragments run a small risk of accidentally
  1100. clobbering local variables in the C<fill_in> function itself. These
  1101. variables all have names that begin with C<$fi_>, so if you stay away
  1102. from those names you'll be safe. (Of course, if you're a real wizard
  1103. you can tamper with them deliberately for exciting effects; this is
  1104. actually how C<$OUT> works.) I can fix this, but it will make the
  1105. package slower to do it, so I would prefer not to. If you are worried
  1106. about this, send me mail and I will show you what to do about it.
  1107. =head2 Alternative Delimiters
  1108. Lorenzo Valdettaro pointed out that if you are using C<Text::Template>
  1109. to generate TeX output, the choice of braces as the program fragment
  1110. delimiters makes you suffer suffer suffer. Starting in version 1.20,
  1111. you can change the choice of delimiters to something other than curly
  1112. braces.
  1113. In either the C<new()> call or the C<fill_in()> call, you can specify
  1114. an alternative set of delimiters with the C<DELIMITERS> option. For
  1115. example, if you would like code fragments to be delimited by C<[@-->
  1116. and C<--@]> instead of C<{> and C<}>, use
  1117. ... DELIMITERS => [ '[@--', '--@]' ], ...
  1118. Note that these delimiters are I<literal strings>, not regexes. (I
  1119. tried for regexes, but it complicates the lexical analysis too much.)
  1120. Note also that C<DELIMITERS> disables the special meaning of the
  1121. backslash, so if you want to include the delimiters in the literal
  1122. text of your template file, you are out of luck---it is up to you to
  1123. choose delimiters that do not conflict with what you are doing. The
  1124. delimiter strings may still appear inside of program fragments as long
  1125. as they nest properly. This means that if for some reason you
  1126. absolutely must have a program fragment that mentions one of the
  1127. delimiters, like this:
  1128. [@--
  1129. print "Oh no, a delimiter: --@]\n"
  1130. --@]
  1131. you may be able to make it work by doing this instead:
  1132. [@--
  1133. # Fake matching delimiter in a comment: [@--
  1134. print "Oh no, a delimiter: --@]\n"
  1135. --@]
  1136. It may be safer to choose delimiters that begin with a newline
  1137. character.
  1138. Because the parsing of templates is simplified by the absence of
  1139. backslash escapes, using alternative C<DELIMITERS> may speed up the
  1140. parsing process by 20-25%. This shows that my original choice of C<{>
  1141. and C<}> was very bad.
  1142. =head2 C<PREPEND> feature and using C<strict> in templates
  1143. Suppose you would like to use C<strict> in your templates to detect
  1144. undeclared variables and the like. But each code fragment is a
  1145. separate lexical scope, so you have to turn on C<strict> at the top of
  1146. each and every code fragment:
  1147. { use strict;
  1148. use vars '$foo';
  1149. $foo = 14;
  1150. ...
  1151. }
  1152. ...
  1153. { # we forgot to put `use strict' here
  1154. my $result = $boo + 12; # $boo is misspelled and should be $foo
  1155. # No error is raised on `$boo'
  1156. }
  1157. Because we didn't put C<use strict> at the top of the second fragment,
  1158. it was only active in the first fragment, and we didn't get any
  1159. C<strict> checking in the second fragment. Then we mispelled C<$foo>
  1160. and the error wasn't caught.
  1161. C<Text::Template> version 1.22 and higher has a new feature to make
  1162. this easier. You can specify that any text at all be automatically
  1163. added to the beginning of each program fragment.
  1164. When you make a call to C<fill_in>, you can specify a
  1165. PREPEND => 'some perl statements here'
  1166. option; the statements will be prepended to each program fragment for
  1167. that one call only. Suppose that the C<fill_in> call included a
  1168. PREPEND => 'use strict;'
  1169. option, and that the template looked like this:
  1170. { use vars '$foo';
  1171. $foo = 14;
  1172. ...
  1173. }
  1174. ...
  1175. { my $result = $boo + 12; # $boo is misspelled and should be $foo
  1176. ...
  1177. }
  1178. The code in the second fragment would fail, because C<$boo> has not
  1179. been declared. C<use strict> was implied, even though you did not
  1180. write it explicitly, because the C<PREPEND> option added it for you
  1181. automatically.
  1182. There are two other ways to do this. At the time you create the
  1183. template object with C<new>, you can also supply a C<PREPEND> option,
  1184. in which case the statements will be prepended each time you fill in
  1185. that template. If the C<fill_in> call has its own C<PREPEND> option,
  1186. this overrides the one specified at the time you created the
  1187. template. Finally, you can make the class method call
  1188. Text::Template->always_prepend('perl statements');
  1189. If you do this, then call calls to C<fill_in> for I<any> template will
  1190. attach the perl statements to the beginning of each program fragment,
  1191. except where overridden by C<PREPEND> options to C<new> or C<fill_in>.
  1192. =head2 Prepending in Derived Classes
  1193. This section is technical, and you should skip it on the first few
  1194. readings.
  1195. Normally there are three places that prepended text could come from.
  1196. It could come from the C<PREPEND> option in the C<fill_in> call, from
  1197. the C<PREPEND> option in the C<new> call that created the template
  1198. object, or from the argument of the C<always_prepend> call.
  1199. C<Text::Template> looks for these three things in order and takes the
  1200. first one that it finds.
  1201. In a subclass of C<Text::Template>, this last possibility is
  1202. ambiguous. Suppose C<S> is a subclass of C<Text::Template>. Should
  1203. Text::Template->always_prepend(...);
  1204. affect objects in class C<Derived>? The answer is that you can have it
  1205. either way.
  1206. The C<always_prepend> value for C<Text::Template> is normally stored
  1207. in a hash variable named C<%GLOBAL_PREPEND> under the key
  1208. C<Text::Template>. When C<Text::Template> looks to see what text to
  1209. prepend, it first looks in the template object itself, and if not, it
  1210. looks in C<$GLOBAL_PREPEND{I<class>}> where I<class> is the class to
  1211. which the template object belongs. If it doesn't find any value, it
  1212. looks in C<$GLOBAL_PREPEND{'Text::Template'}>. This means that
  1213. objects in class C<Derived> I<will> be affected by
  1214. Text::Template->always_prepend(...);
  1215. I<unless> there is also a call to
  1216. Derived->always_prepend(...);
  1217. So when you're designing your derived class, you can arrange to have
  1218. your objects ignore C<Text::Template::always_prepend> calls by simply
  1219. putting C<Derived-E<gt>always_prepend('')> at the top of your module.
  1220. Of course, there is also a final escape hatch: Templates support a
  1221. C<prepend_text> that is used to look up the appropriate text to be
  1222. prepended at C<fill_in> time. Your derived class can override this
  1223. method to get an arbitrary effect.
  1224. =head2 JavaScript
  1225. Jennifer D. St Clair asks:
  1226. > Most of my pages contain JavaScript and Stylesheets.
  1227. > How do I change the template identifier?
  1228. Jennifer is worried about the braces in the JavaScript being taken as
  1229. the delimiters of the Perl program fragments. Of course, disaster
  1230. will ensue when perl tries to evaluate these as if they were Perl
  1231. programs. The best choice is to find some unambiguous delimiter
  1232. strings that you can use in your template instead of curly braces, and
  1233. then use the C<DELIMITERS> option. However, if you can't do this for
  1234. some reason, there are two easy workarounds:
  1235. 1. You can put C<\> in front of C<{>, C<}>, or C<\> to remove its
  1236. special meaning. So, for example, instead of
  1237. if (br== "n3") {
  1238. // etc.
  1239. }
  1240. you can put
  1241. if (br== "n3") \{
  1242. // etc.
  1243. \}
  1244. and it'll come out of the template engine the way you want.
  1245. But here is another method that is probably better. To see how it
  1246. works, first consider what happens if you put this into a template:
  1247. { 'foo' }
  1248. Since it's in braces, it gets evaluated, and obviously, this is going
  1249. to turn into
  1250. foo
  1251. So now here's the trick: In Perl, C<q{...}> is the same as C<'...'>.
  1252. So if we wrote
  1253. {q{foo}}
  1254. it would turn into
  1255. foo
  1256. So for your JavaScript, just write
  1257. {q{if (br== "n3") {
  1258. // etc.
  1259. }}
  1260. }
  1261. and it'll come out as
  1262. if (br== "n3") {
  1263. // etc.
  1264. }
  1265. which is what you want.
  1266. =head2 Shut Up!
  1267. People sometimes try to put an initialization section at the top of
  1268. their templates, like this:
  1269. { ...
  1270. $var = 17;
  1271. }
  1272. Then they complain because there is a C<17> at the top of the output
  1273. that they didn't want to have there.
  1274. Remember that a program fragment is replaced with its own return
  1275. value, and that in Perl the return value of a code block is the value
  1276. of the last expression that was evaluated, which in this case is 17.
  1277. If it didn't do that, you wouldn't be able to write C<{$recipient}>
  1278. and have the recipient filled in.
  1279. To prevent the 17 from appearing in the output is very simple:
  1280. { ...
  1281. $var = 17;
  1282. '';
  1283. }
  1284. Now the last expression evaluated yields the empty string, which is
  1285. invisible. If you don't like the way this looks, use
  1286. { ...
  1287. $var = 17;
  1288. ($SILENTLY);
  1289. }
  1290. instead. Presumably, C<$SILENTLY> has no value, so nothing will be
  1291. interpolated. This is what is known as a `trick'.
  1292. =head2 Compatibility
  1293. Every effort has been made to make this module compatible with older
  1294. versions. The only known exceptions follow:
  1295. The output format of the default C<BROKEN> subroutine has changed
  1296. twice, most recently between versions 1.31 and 1.40.
  1297. Starting in version 1.10, the C<$OUT> variable is arrogated for a
  1298. special meaning. If you had templates before version 1.10 that
  1299. happened to use a variable named C<$OUT>, you will have to change them
  1300. to use some other variable or all sorts of strangeness will result.
  1301. Between versions 0.1b and 1.00 the behavior of the \ metacharacter
  1302. changed. In 0.1b, \\ was special everywhere, and the template
  1303. processor always replaced it with a single backslash before passing
  1304. the code to Perl for evaluation. The rule now is more complicated but
  1305. probably more convenient. See the section on backslash processing,
  1306. below, for a full discussion.
  1307. =head2 Backslash Processing
  1308. In C<Text::Template> beta versions, the backslash was special whenever
  1309. it appeared before a brace or another backslash. That meant that
  1310. while C<{"\n"}> did indeed generate a newline, C<{"\\"}> did not
  1311. generate a backslash, because the code passed to Perl for evaluation
  1312. was C<"\"> which is a syntax error. If you wanted a backslash, you
  1313. would have had to write C<{"\\\\"}>.
  1314. In C<Text::Template> versions 1.00 through 1.10, there was a bug:
  1315. Backslash was special everywhere. In these versions, C<{"\n"}>
  1316. generated the letter C<n>.
  1317. The bug has been corrected in version 1.11, but I did not go back to
  1318. exactly the old rule, because I did not like the idea of having to
  1319. write C<{"\\\\"}> to get one backslash. The rule is now more
  1320. complicated to remember, but probably easier to use. The rule is now:
  1321. Backslashes are always passed to Perl unchanged I<unless> they occur
  1322. as part of a sequence like C<\\\\\\{> or C<\\\\\\}>. In these
  1323. contexts, they are special; C<\\> is replaced with C<\>, and C<\{> and
  1324. C<\}> signal a literal brace.
  1325. Examples:
  1326. \{ foo \}
  1327. is I<not> evaluated, because the C<\> before the braces signals that
  1328. they should be taken literally. The result in the output looks like this:
  1329. { foo }
  1330. This is a syntax error:
  1331. { "foo}" }
  1332. because C<Text::Template> thinks that the code ends at the first C<}>,
  1333. and then gets upset when it sees the second one. To make this work
  1334. correctly, use
  1335. { "foo\}" }
  1336. This passes C<"foo}"> to Perl for evaluation. Note there's no C<\> in
  1337. the evaluated code. If you really want a C<\> in the evaluated code,
  1338. use
  1339. { "foo\\\}" }
  1340. This passes C<"foo\}"> to Perl for evaluation.
  1341. Starting with C<Text::Template> version 1.20, backslash processing is
  1342. disabled if you use the C<DELIMITERS> option to specify alternative
  1343. delimiter strings.
  1344. =head2 A short note about C<$Text::Template::ERROR>
  1345. In the past some people have fretted about `violating the package
  1346. boundary' by examining a variable inside the C<Text::Template>
  1347. package. Don't feel this way. C<$Text::Template::ERROR> is part of
  1348. the published, official interface to this package. It is perfectly OK
  1349. to inspect this variable. The interface is not going to change.
  1350. If it really, really bothers you, you can import a function called
  1351. C<TTerror> that returns the current value of the C<$ERROR> variable.
  1352. So you can say:
  1353. use Text::Template 'TTerror';
  1354. my $template = new Text::Template (SOURCE => $filename);
  1355. unless ($template) {
  1356. my $err = TTerror;
  1357. die "Couldn't make template: $err; aborting";
  1358. }
  1359. I don't see what benefit this has over just doing this:
  1360. use Text::Template;
  1361. my $template = new Text::Template (SOURCE => $filename)
  1362. or die "Couldn't make template: $Text::Template::ERROR; aborting";
  1363. But if it makes you happy to do it that way, go ahead.
  1364. =head2 Sticky Widgets in Template Files
  1365. The C<CGI> module provides functions for `sticky widgets', which are
  1366. form input controls that retain their values from one page to the
  1367. next. Sometimes people want to know how to include these widgets
  1368. into their template output.
  1369. It's totally straightforward. Just call the C<CGI> functions from
  1370. inside the template:
  1371. { $q->checkbox_group(NAME => 'toppings',
  1372. LINEBREAK => true,
  1373. COLUMNS => 3,
  1374. VALUES => \@toppings,
  1375. );
  1376. }
  1377. =head2 Automatic preprocessing of program fragments
  1378. It may be useful to preprocess the program fragments before they are
  1379. evaluated. See C<Text::Template::Preprocess> for more details.
  1380. =head2 Automatic postprocessing of template hunks
  1381. It may be useful to process hunks of output before they are appended to
  1382. the result text. For this, subclass and replace the C<append_text_to_result>
  1383. method. It is passed a list of pairs with these entries:
  1384. handle - a filehandle to which to print the desired output
  1385. out - a ref to a string to which to append, to use if handle is not given
  1386. text - the text that will be appended
  1387. type - where the text came from: TEXT for literal text, PROG for code
  1388. =head2 Author
  1389. Mark Jason Dominus, Plover Systems
  1390. Please send questions and other remarks about this software to
  1391. C<mjd-perl-template+@plover.com>
  1392. You can join a very low-volume (E<lt>10 messages per year) mailing
  1393. list for announcements about this package. Send an empty note to
  1394. C<mjd-perl-template-request@plover.com> to join.
  1395. For updates, visit C<http://www.plover.com/~mjd/perl/Template/>.
  1396. =head2 Support?
  1397. This software is version 1.46. It may have bugs. Suggestions and bug
  1398. reports are always welcome. Send them to
  1399. C<mjd-perl-template+@plover.com>. (That is my address, not the address
  1400. of the mailing list. The mailing list address is a secret.)
  1401. =head1 LICENSE
  1402. Text::Template version 1.46
  1403. Copyright 2013 Mark Jason Dominus
  1404. This program is free software; you can redistribute it and/or
  1405. modify it under the terms of the GNU General Public License as
  1406. published by the Free Software Foundation; either version 2 of the
  1407. License, or (at your option) any later version. You may also can
  1408. redistribute it and/or modify it under the terms of the Perl
  1409. Artistic License.
  1410. This program is distributed in the hope that it will be useful,
  1411. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1412. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1413. GNU General Public License for more details.
  1414. You should have received copies of the GNU General Public License
  1415. along with this program; if not, write to the Free Software
  1416. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  1417. =head1 THANKS
  1418. Many thanks to the following people for offering support,
  1419. encouragement, advice, bug reports, and all the other good stuff.
  1420. David H. Adler /
  1421. Joel Appelbaum /
  1422. Klaus Arnhold /
  1423. AntE<oacute>nio AragE<atilde>o /
  1424. Kevin Atteson /
  1425. Chris.Brezil /
  1426. Mike Brodhead /
  1427. Tom Brown /
  1428. Dr. Frank Bucolo /
  1429. Tim Bunce /
  1430. Juan E. Camacho /
  1431. Itamar Almeida de Carvalho /
  1432. Joseph Cheek /
  1433. Gene Damon /
  1434. San Deng /
  1435. Bob Dougherty /
  1436. Marek Grac /
  1437. Dan Franklin /
  1438. gary at dls.net /
  1439. Todd A. Green /
  1440. Donald L. Greer Jr. /
  1441. Michelangelo Grigni /
  1442. Zac Hansen /
  1443. Tom Henry /
  1444. Jarko Hietaniemi /
  1445. Matt X. Hunter /
  1446. Robert M. Ioffe /
  1447. Daniel LaLiberte /
  1448. Reuven M. Lerner /
  1449. Trip Lilley /
  1450. Yannis Livassof /
  1451. Val Luck /
  1452. Kevin Madsen /
  1453. David Marshall /
  1454. James Mastros /
  1455. Joel Meulenberg /
  1456. Jason Moore /
  1457. Sergey Myasnikov /
  1458. Chris Nandor /
  1459. Bek Oberin /
  1460. Steve Palincsar /
  1461. Ron Pero /
  1462. Hans Persson /
  1463. Sean Roehnelt /
  1464. Jonathan Roy /
  1465. Shabbir J. Safdar /
  1466. Jennifer D. St Clair /
  1467. Uwe Schneider /
  1468. Randal L. Schwartz /
  1469. Michael G Schwern /
  1470. Yonat Sharon /
  1471. Brian C. Shensky /
  1472. Niklas Skoglund /
  1473. Tom Snee /
  1474. Fred Steinberg /
  1475. Hans Stoop /
  1476. Michael J. Suzio /
  1477. Dennis Taylor /
  1478. James H. Thompson /
  1479. Shad Todd /
  1480. Lieven Tomme /
  1481. Lorenzo Valdettaro /
  1482. Larry Virden /
  1483. Andy Wardley /
  1484. Archie Warnock /
  1485. Chris Wesley /
  1486. Matt Womer /
  1487. Andrew G Wood /
  1488. Daini Xie /
  1489. Michaely Yeung
  1490. Special thanks to:
  1491. =over 2
  1492. =item Jonathan Roy
  1493. for telling me how to do the C<Safe> support (I spent two years
  1494. worrying about it, and then Jonathan pointed out that it was trivial.)
  1495. =item Ranjit Bhatnagar
  1496. for demanding less verbose fragments like they have in ASP, for
  1497. helping me figure out the Right Thing, and, especially, for talking me
  1498. out of adding any new syntax. These discussions resulted in the
  1499. C<$OUT> feature.
  1500. =back
  1501. =head2 Bugs and Caveats
  1502. C<my> variables in C<fill_in> are still susceptible to being clobbered
  1503. by template evaluation. They all begin with C<fi_>, so avoid those
  1504. names in your templates.
  1505. The line number information will be wrong if the template's lines are
  1506. not terminated by C<"\n">. You should let me know if this is a
  1507. problem. If you do, I will fix it.
  1508. The C<$OUT> variable has a special meaning in templates, so you cannot
  1509. use it as if it were a regular variable.
  1510. There are not quite enough tests in the test suite.
  1511. =cut