Simple.pm

filter: Statementstmt 94.7% 234 / 247 Branchbran 78.3% 105 / 134 Conditioncond 87.5% 14 / 16 MC/DCmcdc 77.7% 7 / 9 Subroutinesub 96.7% 30 / 31 Podpod 21.4% 3 / 14 totaltotal 87.1% 393 / 451 CC 79 SCAR 23.5
CC
79
Cov
89%
_resolve_section
19.6
_resolve_invert_section
18.0
match_template
13.0
CRAP 10.5
↑ Summary Simple/ContextStack.pm »
1 package Mustache::Simple;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use 5.10.1;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use experimental qw(switch);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 # Don't forget to change the version in the pod
11 4 our $VERSION = version->declare('v1.3.8');
12  
13 4 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 4 ▶use Mustache::Simple::ContextStack v1.3.8;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use Scalar::Util qw( reftype );
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 #use Data::Dumper;
20 #$Data::Dumper::Useqq = 1;
21 #$Data::Dumper::Deparse = 1;
22  
23 =encoding utf8
24  
25 =head1 NAME
26  
27 Mustache::Simple - A simple Mustache Renderer
28  
29 See L<http://mustache.github.com/>.
30  
31 =head1 VERSION
32  
33 This document describes Mustache::Simple version 1.3.8
34  
35 =head1 SYNOPSIS
36  
37 A typical Mustache template:
38  
39 my $template = <<EOT;
40 Hello {{name}}
41 You have just won ${{value}}!
42 {{#in_ca}}
43 Well, ${{taxed_value}}, after taxes.
44 {{/in_ca}}
45 EOT
46  
47 Given the following hashref:
48  
49 my $context = {
50 name => "Chris",
51 value => 10000,
52 taxed_value => 10000 - (10000 * 0.4),
53 in_ca => 1
54 };
55  
56 Will produce the following:
57  
58 Hello Chris
59 You have just won $10000!
60 Well, $6000, after taxes.
61  
62 using the following code:
63  
64 my $tache = new Mustache::Simple(
65 throw => 1
66 );
67 my $output = $tache->render($template, $context);
68  
69 =cut
70  
71 =head1 DESCRIPTION
72  
73 Mustache can be used for HTML, config files, source code - anything. It works
74 by expanding tags in a template using values provided in a hash or object.
75  
76 There are no if statements, else clauses, or
77 for loops. Instead there are only tags. Some tags are replaced with a value,
78 some nothing, and others a series of values.
79  
80 This is a simple perl implementation of the Mustache rendering. It has
81 a single class method, new() to obtain an object and a single instance
82 method render() to convert the template and the hashref into the final
83 output.
84  
85 As of version 1.2.0, it has support for nested contexts, for the dot notation
86 and for the implicit iterator.
87  
88 As of version 1.3.0, it will accept a blessed object. For any C<{{item}}>
89 where the object has a method called item (as returned by C<< $object->can >>),
90 the value will be the return from the method call (with no parameters).
91 If C<< $object->can(item) >> returns C<undef>, the object will be treated
92 as a hash and the value looked up directly. See L</MANAGING OBJECTS> below.
93  
94 As of version 1.3.6, if a method call on a blessed object returns an array,
95 a C<{{#item}}> section will iterate over the array. This also works
96 recursively, so a method can return an array of objects.
97  
98 =head2 Rationale
99  
100 I wanted a simple rendering tool for Mustache that did not require any
101 subclassing.
102  
103 =cut
104  
105 #############################################################
106 ##
107 ## Helper Functions
108 ##
109 ##
110  
111 27 ▶sub dottags($;$) {
Subroutine dottags: called CC=2 SCAR=6.9
Pod undocumented
112 27 my $tag = shift;
113 27 ▶ my $type = shift // '';
Condition100%2/2
shift() // ""
l!l
216
MC/DC100%1/1
shift() // ""
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
114 27 my @dots = $tag =~ /(.*?)\.(.*)/;
115 27 my @tags = (
116 { pre => '', type => '#', txt => $dots[0] },
117 { pre => '', type => $type, txt => $dots[1] },
118 { pre => '', type => '/', txt => $dots[0] },
119 );
120 27 return @tags;
121 }
122  
123 # Generate a regular expression for iteration
124 # Passed the open and close tags
125 # Returns the regular expression
126 135 ▶sub tag_match(@) {
Subroutine tag_match: called CC=1 SCAR=0.0
Pod undocumented
127 135 my ( $open, $close ) = @_;
128  
129 # Much of this regular expression stolen from Template::Mustache
130 135 qr/
131 (?<pre> .*?) # Text up to opening tag
132 (?<tab> ^ \s*)? # Indent white space
133 (?: \Q$open\E \s*) # Start of tag
134 (?:
135 (?<type> =) \s* (?<txt>.+?) \s* = | # Change delimiters
136 (?<type> {) \s* (?<txt>.+?) \s* } | # Unescaped
137 (?<type> &) \s* (?<txt>.+?) | # Unescaped
138 (?<type> [#^>\/!]?) \s* (?<txt>.+?) # Normal tags
139 )
140 (?: \s* \Q$close\E) # End of tag
141 /xsm;
142 }
143  
144 # Escape HTML entities
145 # Passed a string
146 # Returns an escaped string
147 114 ▶sub escape($) {
Subroutine escape: called CC=1 SCAR=0.0
Pod undocumented
148 114 local $_ = shift;
149 114 s/&/&amp;/g;
150 114 s/"/&quot;/g;
151 114 s/</&lt;/g;
152 114 s/>/&gt;/g;
153 114 return $_;
154 }
155  
156 # Reassemble the source code for an array of tags
157 # Passed an array of tags
158 # Returns the original source (roughly)
159 5 ▶sub reassemble(@) {
Subroutine reassemble: called CC=2 SCAR=6.9
Pod undocumented
160 5 my @tags = @_;
161 5 my $last = pop @tags;
162 5 my $ans = '';
163 5 local $_;
164 4 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
165 5 $ans .= "$_->{pre}$_->{tab}\{\{$_->{type}$_->{txt}\}\}" foreach (@tags);
166 5 return $ans . $last->{pre};
167 }
168  
169 #############################################################
170 ##
171 ## Class Functions
172 ##
173 ##
174  
175 =head1 METHODS
176  
177 =head2 Creating a new Mustache::Simple object
178  
179 =over
180  
181 =item new
182  
183 my $tache = new Mustache::Simple(%options)
184  
185 =back
186  
187 =head3 Parameters:
188  
189 =over
190  
191 =item path
192  
193 The path from which to load templates and partials. This may be
194 a string or a reference to an array of strings. If it is a reference,
195 each string will be searched in order.
196  
197 Default: '.'
198  
199 =item extension
200  
201 The extension to add to filenames when reading them off disk. The
202 '.' should not be included as this will be added automatically.
203  
204 Default: 'mustache'
205  
206 =item throw
207  
208 If set to a true value, Mustache::Simple will croak when there
209 is no key in the context hash for a given tag.
210  
211 Default: undef
212  
213 =item partial
214  
215 This may be set to a subroutine to be called to generate the
216 filename or the template for a partial. If it is not set, partials
217 will be loaded using the same parameters as render().
218  
219 Default: undef
220  
221 =back
222  
223 =cut
224  
225 98 ▶sub new {
Subroutine new: called CC=2 SCAR=7.1
Pod documented
226 98 my $class = shift;
227 my %options =
228 0 ▶ @_ == 1 ? %{ $_[0] } : @_; # Allow a hash to be passed, in case
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 0 98 98
229 98 my %defaults = (
230 path => '.',
231 extension => 'mustache',
232 delimiters => [qw({{ }})],
233 stack => new Mustache::Simple::ContextStack,
234 );
235 98 %options = ( %defaults, %options );
236 98 my $self = \%options;
237 98 bless $self, $class;
238 }
239  
240 #############################################################
241 ##
242 ## Private Instance Functions
243 ##
244 ##
245  
246 # Breaks the template into separate tags, preserving the text
247 # Returns an array ref of the tags and the trailing text
248 122 ▶sub match_template {
Subroutine match_template: called CC=13 SCAR=25.6
Pod undocumented
249 122 my $self = shift;
250 122 my $template = shift;
251 my $match =
252 122 tag_match( @{ $self->{delimiters} } ); # start with standard delimiters
253 122 my @tags;
254 my $afters;
255 122 ▶ while ( $template =~ /$match/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($template =~ /$match/g) 263 122 385
256 263 my %tag = %+; # pick up named parts from the regex
257 263 ▶ if ( $tag{type} eq '=' ) # change delimiters
Branch: 1 branch
BranchTrueFalseTotal
if ($tag{"type"} eq "=") 13 250 263
258 {
259 13 my @delimiters = split /\s/, $tag{txt};
260 13 $self->{delimiters} = \@delimiters;
261 13 $match = tag_match(@delimiters);
262 }
263 263 $afters = $'; # save off the rest in case it's done
264 263 push @tags, \%tag; # put the tag into the array
265 }
266 122 ▶ return \@tags, $template if ( @tags == 0 ); # no tags, it's all afters
Branch: 1 branch
BranchTrueFalseTotal
if @tags == 0 15 107 122
267 107 for ( 1 .. $#tags ) { # lose a leading LF after sections
268 156 ▶ $tags[$_]->{pre} =~ s/^\r?\n// if $tags[ $_ - 1 ]->{type} =~ m{^[#/^]$};
Branch: 1 branch
BranchTrueFalseTotal
if $tags[$_ - 1]{"type"} =~ m[^[#/^]$] 74 82 156
269 }
270 107 ▶ if ( @tags > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tags > 1) 57 50 107
271 $tags[1]->{pre} =~ s/^\r?\n//
272 57 ▶ if $tags[0]->{type} eq '=' and $tags[0]->{pre} =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $tags[0]{"type"} eq "=" and $tags[0]{"pre"} =~ /^\s*$/ 3 54 57
Condition100%3/3
$tags[0]{"type"} eq "=" and $tags[0]{"pre"} =~ /^\s*$/
!ll&&!rl&&r
5313
MC/DC100%2/2
$tags[0]{"type"} eq "=" and $tags[0]{"pre"} =~ /^\s*$/
$tags[0]{"type"} eq "=" $tags[0]{"pre"} =~ /^\s*$/
Truth table100%3/3
A and B
A= $tags[0]{"type"} eq "="B= $tags[0]{"pre"} =~ /^\s*$/
ABresult
0X0
100
111
273 }
274 107 foreach ( 0 .. $#tags ) {
275 263 ▶ $tags[$_]->{pre} =~ s/^\r?\n// if $tags[$_]->{type} =~ m{^[!]$};
Branch: 1 branch
BranchTrueFalseTotal
if $tags[$_]{"type"} =~ /^[!]$/ 7 256 263
276 263 ▶ $tags[$_]->{pre} =~ s/\r?\n$// if $tags[$_]->{type} =~ m{^[=]$};
Branch: 1 branch
BranchTrueFalseTotal
if $tags[$_]{"type"} =~ /^[=]$/ 13 250 263
277 }
278  
279 # and from the trailing text
280 107 ▶ $afters =~ s/^\r?\n// if $tags[$#tags]->{type} =~ m{^[/!]$};
Branch: 1 branch
BranchTrueFalseTotal
if $tags[$#tags]{"type"} =~ m[^[/!]$] 55 52 107
281 107 return \@tags, $afters;
282 }
283  
284 # Performs partial includes
285 # Passed the current context, it calls the user code if any
286 # Returns the partial rendered in the current context
287 11 ▶sub include_partial {
Subroutine include_partial: called CC=2 SCAR=7.0
Pod undocumented
288 11 my $self = shift;
289 11 my $tag = shift;
290 11 my $result;
291 11 ▶ $tag = $self->partial->($tag) if ( ref $self->partial eq 'CODE' );
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->partial eq "CODE" 11 0 11
292 11 $self->render($tag);
293 }
294  
295 137 ▶sub _resolve_variable {
Subroutine _resolve_variable: called CC=8 SCAR=20.8
296 137 my $self = shift;
297 137 my ($tag) = @_;
298 137 my $txt;
299 137 ▶ if ( $tag->{txt} eq '.' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($tag->{'txt'} eq '.') { } 10 127 137
elsif ($tag->{'txt'} =~ /\./) { } 21 106 127
300 10 $txt = $self->{stack}->top;
301 }
302 elsif ( $tag->{txt} =~ /\./ ) {
303 21 my @dots = dottags $tag->{txt}, $tag->{type};
304 21 $txt = $self->resolve( undef, @dots );
305 }
306 else {
307 106 $txt = $self->find( $tag->{txt} ); # get the entry from the context
308 106 ▶ if ( defined $txt ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $txt) { } 103 3 106
309 103 ▶ if ( ref $txt eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $txt eq "CODE") 8 95 103
310 8 my $saved = $self->{delimiters};
311 8 $self->{delimiters} = [qw({{ }})];
312 8 $txt = $self->render( $txt->() );
313 8 $self->{delimiters} = $saved;
314 }
315 }
316 else {
317 3 ▶ croak qq(No context for "$tag->{txt}") if $self->throw;
Branch: 1 branch
BranchTrueFalseTotal
if $self->throw 0 3 3
318 3 $txt = '';
319 }
320 }
321 137 ▶ $txt = "$tag->{tab}$txt" if $tag->{tab}; # replace the indent
Branch: 1 branch
BranchTrueFalseTotal
if $tag->{"tab"} 8 129 137
322 137 ▶ return $tag->{type} ? $txt : escape $txt;
Branch: 1 branch
BranchTrueFalseTotal
$tag->{'type'} ? : 23 114 137
323 }
324  
325 66 ▶sub _resolve_section {
Subroutine _resolve_section: called CC=18 SCAR=29.7
326 66 my $self = shift;
327 66 my ( $tags, $i ) = @_;
328 66 my $tag = $tags->[$i]; # the current tag
329 66 my $j;
330 66 my $nested = 0;
331 66 ▶ for ( $j = $i + 1; $j < @$tags; $j++ ) # find the end
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @$tags) 276 0 276
332 {
333 276 ▶ if ( $tag->{txt} eq $tags->[$j]->{txt} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag->{"txt"} eq $tags->[$j]{"txt"}) 70 206 276
334 $nested++, next
335 70 ▶ if $tags->[$j]->{type} eq '#'; # nested sections with the
Branch: 1 branch
BranchTrueFalseTotal
if $tags->[$j]{"type"} eq "#" 2 68 70
336 68 ▶ if ( $tags->[$j]->{type} eq '/' ) # same name
Branch: 1 branch
BranchTrueFalseTotal
if ($tags->[$j]{"type"} eq "/") 68 0 68
337 {
338 68 ▶ next if $nested--;
Branch: 1 branch
BranchTrueFalseTotal
if $nested-- 2 66 68
339 66 last;
340 }
341 }
342 }
343 66 ▶ croak 'No end tag found for {{#' . $tag->{txt} . '}}' if $j == @$tags;
Branch: 1 branch
BranchTrueFalseTotal
if $j == @$tags 0 66 66
344 66 my @subtags = @$tags[ $i + 1 .. $j ]; # get the tags for the section
345 66 my $txt;
346 66 ▶ if ( $tag->{txt} =~ /\./ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag->{'txt'} =~ /\./) { } 3 63 66
347 3 my @dots = dottags( $tag->{txt} );
348 3 $txt = $self->resolve( undef, @dots );
349 }
350 else {
351 # wantarray!!!
352 63 my @ret = $self->find( $tag->{txt} ); # get the entry from the context
353 63 ▶ if ( scalar @ret == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @ret == 0) { } 0 63 63
elsif (scalar @ret == 1) { } 63 0 63
354 0 $txt = undef;
355 }
356 elsif ( scalar @ret == 1 ) {
357 63 $txt = $ret[0];
358 }
359 else {
360 0 $txt = \@ret;
361 }
362 }
363 66 my $result = '';
364 66 my $reftxt = reftype $txt;
365 66 ▶ if ( not defined $reftxt ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $reftxt) 17 49 66
366 17 ▶ $result .= $self->resolve( undef, @subtags ) if $txt;
Branch: 1 branch
BranchTrueFalseTotal
if $txt 12 5 17
367 17 return ( $result, $j );
368 }
369 49 ▶ if ( 'ARRAY' eq $reftxt ) { # an array of hashes (hopefully)
Branch: 1 branch
BranchTrueFalseTotal
if ("ARRAY" eq $reftxt) 6 43 49
370 6 $result .= $self->resolve( $_, @subtags ) foreach @$txt;
371 6 return ( $result, $j );
372 }
373 43 ▶ if ( 'CODE' eq $reftxt ) { # call user code which may call render()
Branch: 1 branch
BranchTrueFalseTotal
if ("CODE" eq $reftxt) 5 38 43
374 5 $result .= $self->render( $txt->( reassemble @subtags ) );
375 5 return ( $result, $j );
376 }
377 38 ▶ if ( 'HASH' eq $reftxt ) { # use the hash as context
Branch: 1 branch
BranchTrueFalseTotal
if ("HASH" eq $reftxt) 38 0 38
378 38 ▶ return ( $result, $j ) unless scalar %$txt;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar %$txt 5 33 38
379 33 $result .= $self->resolve( $txt, @subtags );
380 33 return ( $result, $j );
381 }
382 0 ▶ $result .= $self->resolve( undef, @subtags ) if $txt;
Branch: 1 branch
BranchTrueFalseTotal
if $txt 0 0 0
383 0 return ( $result, $j );
384 }
385  
386 20 ▶sub _resolve_invert_section {
Subroutine _resolve_invert_section: called CC=17 SCAR=28.9
387 20 my $self = shift;
388 20 my ( $tags, $i ) = @_;
389 20 my $tag = $tags->[$i]; # the current tag
390 20 my $j;
391 20 my $nested = 0;
392 20 ▶ for ( $j = $i + 1; $j < @$tags; $j++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @$tags) 29 0 29
393 29 ▶ if ( $tag->{txt} eq $tags->[$j]->{txt} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag->{"txt"} eq $tags->[$j]{"txt"}) 24 5 29
394 $nested++, next
395 24 ▶ if $tags->[$j]->{type} eq '^'; # nested sections with the
Branch: 1 branch
BranchTrueFalseTotal
if $tags->[$j]{"type"} eq "^" 2 22 24
396 22 ▶ if ( $tags->[$j]->{type} eq '/' ) # same name
Branch: 1 branch
BranchTrueFalseTotal
if ($tags->[$j]{"type"} eq "/") 22 0 22
397 {
398 22 ▶ next if $nested--;
Branch: 1 branch
BranchTrueFalseTotal
if $nested-- 2 20 22
399 20 last;
400 }
401 }
402 }
403 20 ▶ croak 'No end tag found for {{#' . $tag->{txt} . '}}' if $j == @$tags;
Branch: 1 branch
BranchTrueFalseTotal
if $j == @$tags 0 20 20
404 20 my @subtags = @$tags[ $i + 1 .. $j ];
405 20 my $txt;
406 20 ▶ if ( $tag->{txt} =~ /\./ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag->{'txt'} =~ /\./) { } 3 17 20
407 3 my @dots = dottags( $tag->{txt} );
408 3 $txt = $self->resolve( undef, @dots );
409 }
410 else {
411 17 $txt = $self->find( $tag->{txt} ); # get the entry from the context
412 }
413 20 my $ans = '';
414 20 my $reftxt = reftype $txt;
415 20 ▶ if ( not defined $reftxt ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $reftxt) { } 16 4 20
elsif ('ARRAY' eq $reftxt) { } 2 2 4
elsif ('HASH' eq $reftxt) { } 1 1 2
elsif ('CODE' eq $reftxt) { } 1 0 1
416 16 ▶ $ans = $self->resolve( undef, @subtags ) unless $txt;
Branch: 1 branch
BranchTrueFalseTotal
unless $txt 13 3 16
417 }
418 elsif ( 'ARRAY' eq $reftxt ) {
419 2 ▶ $ans = $self->resolve( undef, @subtags ) if @$txt == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @$txt == 0 1 1 2
420 }
421 elsif ( 'HASH' eq $reftxt ) {
422 1 ▶ $ans = $self->resolve( undef, @subtags ) if keys %$txt == 0;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$txt == 0 0 1 1
423 }
424 elsif ( 'CODE' eq $reftxt ) {
425  
426 # Y
427 # $ans = $self->resolve(undef, @subtags) unless &$txt;
428 # The above line is rem'd out to comply with the test:
429 # 'Lambdas used for inverted sections should be considered truthy.'
430 # although I'm not sure I agree with it.
431 1 $ans = '';
432 }
433 else {
434 0 ▶ $ans = $self->resolve( undef, @subtags ) unless $txt;
Branch: 1 branch
BranchTrueFalseTotal
unless $txt 0 0 0
435 }
436 20 ▶ $ans = "$tag->{tab}$ans" if $tag->{tab}; # replace the indent
Branch: 1 branch
BranchTrueFalseTotal
if $tag->{"tab"} 0 20 20
437 20 return ( $ans, $j );
438 }
439  
440 # This is the main worker function. It builds up the result from the tags.
441 # Passed the current context and the array of tags
442 # Returns the final text
443 # Note, this is called recursively, directly for sections and
444 # indirectly via render() for partials
445 222 ▶sub resolve {
Subroutine resolve: called CC=10 SCAR=23.0
Pod undocumented
446 222 my $self = shift;
447 222 ▶ my $context = shift // {};
Condition100%2/2
shift() // {}
l!l
16953
MC/DC100%1/1
shift() // {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
448 222 $self->push($context);
449 222 my @tags = @_;
450 222 my $result = '';
451 222 ▶ for ( my $i = 0; $i < @tags; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @tags) 327 222 549
452 327 my $tag = $tags[$i]; # the current tag
453 327 $result .= $tag->{pre}; # add in the intervening text
454 327 ▶ if ( $tag->{type} eq '!' or $tag->{type} eq '/' or $tag->{type} eq '=' ) {
Branch: 5 branches
BranchTrueFalseTotal
if ($tag->{'type'} eq '!' or $tag->{'type'} eq '/' or $tag->{'type'} eq '=') { } 93 234 327
elsif ($tag->{'type'} eq '>') { } 11 223 234
elsif ($tag->{'type'} eq '^') { } 20 203 223
elsif ($tag->{'type'} eq '#') { } 66 137 203
elsif ($tag->{'type'} =~ /^([{&])?$/) { } 137 0 137
Condition100%6/6
$tag->{"type"} eq "!" or $tag->{"type"} eq "/" or $tag->{"type"} eq "="
l!l&&r!l&&!r
8013234
$tag->{"type"} eq "!" or $tag->{"type"} eq "/"
l!l&&r!l&&!r
773247
MC/DC100%3/3
$tag->{"type"} eq "!" or $tag->{"type"} eq "/" or $tag->{"type"} eq "="
$tag->{"type"} eq "!" $tag->{"type"} eq "/" $tag->{"type"} eq "="
Truth table100%4/4
A or B or C
A= $tag->{"type"} eq "!"B= $tag->{"type"} eq "/"C= $tag->{"type"} eq "="
ABCresult
1XX1
01X1
0011
0000
455 # given ($tag->{type})
456 # when ('!') { # it's a comment
457 # # $result .= $tag->{tab} if $tag->{tab};
458 # }
459 # when ('/') { break; } # it's a section end - skip
460 # when ('=') { break; } # delimiter change
461 93 next;
462 }
463 elsif ( $tag->{type} eq '>' ) { # partial - see include_partial()
464 11 my $saved = $self->{delimiters};
465 11 $self->{delimiters} = [qw({{ }})];
466 11 $result .= $self->include_partial( $tag->{txt} );
467 11 $self->{delimiters} = $saved;
468 }
469 elsif ( $tag->{type} eq '^' ) { # inverse section
470 20 my ( $out, $j ) = $self->_resolve_invert_section( \@tags, $i );
471 20 $i = $j;
472 20 $result .= $out;
473 }
474 elsif ( $tag->{type} eq '#' ) { # it's a section start
475 66 my ( $out, $j ) = $self->_resolve_section( \@tags, $i );
476 66 $i = $j;
477 66 $result .= $out;
478 }
479 elsif ( $tag->{type} =~ /^([{&])?$/ ) {
480 137 $result .= $self->_resolve_variable( $tag, );
481 }
482 else {
483 0 croak "Unknown tag type in \{\{$_$tag->{txt}}}";
484 }
485 }
486 222 $self->pop;
487 222 return $result;
488 }
489  
490 # Push something a context onto the stack
491 222 ▶sub push {
Subroutine push: called CC=1 SCAR=0.0
Pod undocumented
492 222 my $self = shift;
493 222 my $value = shift;
494 222 $self->{stack}->push($value);
495 }
496  
497 # Pop the context back off the stack
498 222 ▶sub pop {
Subroutine pop: called CC=1 SCAR=0.0
Pod undocumented
499 222 my $self = shift;
500 222 my $value = $self->{stack}->pop;
501 222 return $value;
502 }
503  
504 # Find a value on the stack
505 186 ▶sub find {
Subroutine find: called CC=1 SCAR=0.0
Pod undocumented
506 186 my $self = shift;
507 186 my $value = shift;
508 186 return $self->{stack}->search($value);
509 }
510  
511 # Given a path and a filename
512 # returns the first match that exists
513 sub getfile($$);
514  
515 14 ▶sub getfile($$) {
Subroutine getfile: called CC=7 SCAR=23.4
Pod undocumented
516 14 my ( $path, $filename ) = @_;
517 14 $filename
518 =~ s/\r?\n$//; # not chomp $filename because of the possibility of \r\n
519 14 ▶ return if $filename =~ /\r?\n/;
Branch: 1 branch
BranchTrueFalseTotal
if $filename =~ /\r?\n/ 1 13 14
520 13 my $fullfile;
521 13 ▶ if ( ref $path && ref $path eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $path and ref $path eq 'ARRAY') { } 0 13 13
Condition33%1/3
ref $path and ref $path eq "ARRAY"
!ll&&!rl&&r
1300
MC/DC0%0/2
ref $path and ref $path eq "ARRAY"
ref $path ref $path eq "ARRAY"
Truth table33%1/3
A and B
A= ref $pathB= ref $path eq "ARRAY"
ABresult
0X0
100
111
522 0 foreach (@$path) {
523 0 $fullfile = getfile $_, $filename;
524 0 ▶ last if $fullfile;
Branch: 1 branch
BranchTrueFalseTotal
if $fullfile 0 0 0
525 }
526 }
527 else {
528 13 $fullfile = File::Spec->catfile( $path, $filename );
529 13 ▶ undef $fullfile unless -e $fullfile;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $fullfile 13 0 13
530 }
531 13 return $fullfile;
532 }
533  
534 #############################################################
535 ##
536 ## Public Instance Functions
537 ##
538 ##
539  
540 4 ▶use constant functions => qw(path extension throw partial);
Subroutine BEGIN: called CC=1 SCAR=0.0
541  
542 =head2 Configuration Methods
543  
544 The configuration methods match the %options array thay may be passed
545 to new().
546  
547 Each option may be called with a non-false value to set the option
548 and will return the new value. If called without a value, it will return
549 the current value.
550  
551 =over
552  
553 =item path()
554  
555 $tache->path('/some/new/template/path');
556 or
557 $tache->path([ qw{/some/new/template/path .} ]);
558 my $path = $tache->path; # defaults to '.'
559  
560 =item extension()
561  
562 $tache->extension('html');
563 my $extension = $tache->extension; # defaults to 'mustache'
564  
565 =item throw()
566  
567 $tache->throw(1);
568 my $throwing = $tache->throw; # defaults to undef
569  
570 =item partial()
571  
572 $tache->partial(\&resolve_partials)
573 my $partial = $tache->partial # defaults to undef
574  
575 =back
576  
577 =cut
578  
579 53 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=3 SCAR=11.1
580 53 my $self = shift;
581 53 my $class = ref $self;
582 53 my $value = shift;
583 53 ( my $name = our $AUTOLOAD ) =~ s/.*:://;
584 53 my %ok = map { ( $_, 1 ) } functions;
585 53 ▶ croak "Unknown function $class->$name()" unless $ok{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok{$name} 0 53 53
586 53 ▶ $self->{$name} = $value if $value;
Branch: 1 branch
BranchTrueFalseTotal
if $value 0 53 53
587 53 return $self->{$name};
588 }
589  
590 # Prevent it being caught by AUTOLOAD
591 0 ▶sub DESTROY {
Subroutine DESTROY: not called CC=1 SCAR=0.0
592 }
593  
594 =head2 Instance methods
595  
596 =over
597  
598 =item read_file()
599  
600 my $template = read_file('templatefile');
601  
602 You will not usually need to call this directly as it's called by
603 L</render> to load the file. If it is passed a string that looks like
604 a template (i.e. has {{ in it) it simply returns it. Similarly, if,
605 after prepending the path and adding the suffix, it cannot load the file,
606 it simply returns the original string.
607  
608 =back
609  
610 =cut
611  
612 122 ▶sub read_file($) {
Subroutine read_file: called CC=5 SCAR=17.6
Pod documented
613 122 my $self = shift;
614 122 my $file = shift;
615 122 ▶ return '' unless $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file 1 121 122
616 121 ▶ return $file if $file =~ /\{\{/;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\{\{/ 107 14 121
617 14 my $extension = $self->extension;
618 14 ( my $fullfile = $file ) =~ s/(\.$extension)?$/.$extension/;
619 14 my $filepath = getfile $self->path, $fullfile;
620 14 ▶ return $file unless $filepath;
Branch: 1 branch
BranchTrueFalseTotal
unless $filepath 14 0 14
621 0 local $/;
622 0 ▶ open my $hand, "<:utf8", $filepath or croak "Can't open $filepath: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $hand, "<:utf8", $filepath or croak("Can't open ${filepath}: $!") 0 0 0
623 0 <$hand>;
624 }
625  
626 =over
627  
628 =item render()
629  
630 my $context = {
631 "name" => "Chris",
632 "value" => 10000,
633 "taxed_value" => 10000 - (10000 * 0.4),
634 "in_ca" => true
635 }
636 my $html = $tache->render('templatefile', $context);
637  
638 This is the main entry-point for rendering templates. It can be passed
639 either a full template or path to a template file. See L</read_file>
640 for details of how the file is loaded. It must also be passed a hashref
641 containing the main context.
642  
643 In callbacks (sections like C< {{#this}} > with a subroutine in the context),
644 you may call render on the passed string and the current context will be
645 remembered. For example:
646  
647 {
648 name => "Willy",
649 wrapped => sub {
650 my $text = shift;
651 chomp $text;
652 return "<b>" . $tache->render($text) . "</b>\n";
653 }
654 }
655  
656 Alternatively, you may pass in an entirely new context when calling
657 render() from a callback.
658  
659 =back
660  
661 =cut
662  
663 122 ▶sub render {
Subroutine render: called CC=2 SCAR=6.9
Pod documented
664 122 my $self = shift;
665 122 my ( $template, $context ) = @_;
666 122 ▶ $context = {} unless $context;
Branch: 1 branch
BranchTrueFalseTotal
unless $context 24 98 122
667  
668 # say "\$template = $template, ref \$context = ", ref $context;
669 # print Dumper $context;
670 122 $template = $self->read_file($template);
671 122 my ( $tags, $tail ) = $self->match_template($template);
672  
673 # print reassemble(@$tags), $tail; exit;
674 122 my $result = $self->resolve( $context, @$tags ) . $tail;
675 122 return $result;
676 }
677  
678 =head1 COMPLIANCE WITH THE STANDARD
679  
680 The original standard for Mustache was defined at the
681 L<Mustache Manual|http://mustache.github.io/mustache.5.html>
682 and this version of L<Mustache::Simple> was designed to comply
683 with just that. Since then, the standard for Mustache seems to be
684 defined by the L<Mustache Spec|https://github.com/mustache/spec>.
685  
686 The test suite on this version skips a number of tests
687 in the Spec, all of which relate to Decimals or White Space.
688 It passes all the other tests. The YAML from the Spec is built
689 into the test suite.
690  
691 =head1 MANAGING OBJECTS
692  
693 If a blessed object is passed in (at any level) as the context for
694 rendering a template, L<Mustache::Simple> will check each tag to
695 see if it can be called as a method on the object. To achieve this, it
696 calls C<can> from L<UNIVERSAL|http://perldoc.perl.org/UNIVERSAL.html>
697 on the object. If C<< $object->can(tag) >>
698 returns code, this code will be called (with no parameters). Otherwise,
699 if the object is based on an underlying HASH, it will be treated as that
700 HASH. This works well for objects with AUTOLOADed "getters".
701  
702 For example:
703  
704 package Test::Mustache;
705  
706 sub new
707 {
708 my $class = shift;
709 my %params = @_;
710 bless \%params, $class;
711 }
712  
713 sub name # Ensure the name starts with a capital
714 {
715 my $self = shift;
716 (my $name = $self->{name}) =~ s/.*/\L\u$&/;
717 return $name;
718 }
719  
720 sub AUTOLOAD # generic getter / setter
721 {
722 my $self = shift;
723 my $value = shift;
724 (my $method = our $AUTOLOAD) =~ s/.*:://;
725 $self->{$method} = $value if defined $value;
726 return $self->{$method};
727 }
728  
729 sub DESTROY { }
730  
731 Using the above object as C<$object>, C<{{name}}> would call
732 C<< $object->can('name') >> which would return a reference to
733 the C<name> method and thus that method would be called as a
734 "getter". On a call to C<{{address}}>, C<< $object->can >> would
735 return undef and therefore C<< $object->{address} >> would be
736 used.
737  
738 This is usually what you want as it avoids the call to C<< $object->AUTOLOAD >>
739 for each simple lookup. If, however, you want something different to
740 happen, you either need to declare a "Forward Declaration"
741 (see L<perlsub|http://perldoc.perl.org/perlsub.html>)
742 or you need to override the object's C<can>
743 (see L<UNIVERSAL|http://perldoc.perl.org/UNIVERSAL.html>).
744  
745 =head1 BUGS
746  
747 =over
748  
749 =item White Space
750  
751 Much of the more esoteric white-space handling specified in
752 L<The Mustache Spec|https://github.com/mustache/spec> is not strictly adhered to
753 in this version. Most of this will be addressed in a future version.
754  
755 Because of this, the following tests from the Mustache Spec are skipped:
756  
757 =over
758  
759 =item * Indented Inline
760  
761 =item * Indented Inline Sections
762  
763 =item * Internal Whitespace
764  
765 =item * Standalone Indentation
766  
767 =item * Standalone Indented Lines
768  
769 =item * Standalone Line Endings
770  
771 =item * Standalone Without Newline
772  
773 =item * Standalone Without Previous Line
774  
775 =back
776  
777 =item Decimal Interpolation
778  
779 The spec implies that the template C<"{{power}} jiggawatts!"> when passed
780 C<{ power: "1.210" }> should return C<"1.21 jiggawatts!">. I believe this to
781 be wrong and simply a mistake in the YAML of the relevant tests or possibly
782 in L<YAML::XS>. I am far from being a YAML expert.
783  
784 Clearly C<{ power : 1.210 }> would have the desired effect.
785  
786 Because of this, all tests matching C</Decimal/> have been skipped. We can just
787 assume that Perl will do the right thing.
788  
789 =back
790  
791 =head1 EXPORTS
792  
793 Nothing.
794  
795 =head1 SEE ALSO
796  
797 L<Template::Mustache|Template::Mustache> - a much more complex module that is
798 designed to be subclassed for each template.
799  
800 =head1 AUTHOR INFORMATION
801  
802 Cliff Stanford C<< <cliff@may.be> >>
803  
804 =head1 SOURCE REPOSITORY
805  
806 The source is maintained at a public Github repository at
807 L<https://github.com/CliffS/mustache-simple>. Feel free to fork
808 it and to help me fix some of the above issues. Please leave any
809 bugs or issues on the L<Issues|https://github.com/CliffS/mustache-simple/issues>
810 page and I will be notified.
811  
812 =head1 LICENCE AND COPYRIGHT
813  
814 Copyright © 2014, Cliff Stanford C<< <cliff@may.be> >>. All rights reserved.
815  
816 This module is free software; you can redistribute it and/or
817 modify it under the same terms as Perl itself.
818  
819 =cut
820  
821 4 1;
822  
↑ Summary Simple/ContextStack.pm »