lib/Template/EmbeddedPerl.pm

filter: Statementstmt 100% 548 / 548 Branchbran 83.1% 143 / 172 Conditioncond 61.0% 58 / 95 MC/DCmcdc 44.4% 24 / 54 Subroutinesub 100% 105 / 105 Podpod 74.0% 20 / 27 totaltotal 89.7% 898 / 1001 CC 126 SCAR 17.2
CC
126
Cov
92%
parse_template
18.0
compile
11.0
_construct_view
11.0
CRAP 5.6
« lib/Template/EmbeddedPerl/SafeString.pm ↑ Summary lib/Template/EmbeddedPerl/Utils.pm »
1 package Template::EmbeddedPerl;
2  
3 92 our $VERSION = '0.001016';
4 67 $VERSION = eval $VERSION;
5  
6 27 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 27 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 27 ▶use PPI::Document;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 27 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 27 ▶use Digest::MD5;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 26 ▶use Encode qw(encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 26 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 26 ▶use Template::EmbeddedPerl::Arguments;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 26 ▶use Template::EmbeddedPerl::Compiled;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 26 ▶use Template::EmbeddedPerl::RenderContext;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 26 ▶use Template::EmbeddedPerl::RenderFrame;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 26 ▶use Template::EmbeddedPerl::Utils qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
20 diagnostic_source_label
21 normalize_linefeeds
22 generate_error_message
23 26 );
24 26 ▶use Template::EmbeddedPerl::SafeString;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 26 ▶use Regexp::Common qw /balanced/;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 78 our $ACTIVE_RENDERER;
28  
29 # used for the variable interpolation feature
30 153 my $balanced_parens = $RE{balanced}{-parens => '()'};
31 153 my $balanced_brackets = $RE{balanced}{-parens => '[]'};
32 149 my $balanced_curlies = $RE{balanced}{-parens => '{}'};
33  
34 # Custom recursive pattern for ${...}
35 138 my $balanced_dollar_curly = qr/
36 \$\{
37 (?<brace_content>
38 [^{}]+
39 |
40 \{ (?&brace_content) \}
41 )*
42 \}
43 /x;
44  
45 139 my $variable_regex = qr/
46 (?<!\\) # Negative lookbehind for backslash
47 (?<variable>
48 (?: # Variable can be in one of two formats:
49 \$ \w+ (?: :: \w+ )* # 1. $variable, possibly with package names
50 |
51 $balanced_dollar_curly # 2. ${...}, using balanced delimiters
52 )
53 (?: # Non-capturing group for operators
54 (?:
55 (\s*)->(\s*) # Dereference operator
56 (?:
57 \$? \w+ # Method name, possibly starting with $
58 (?: $balanced_parens )? # Optional method arguments
59 |
60 $balanced_brackets # Array dereference after '->'
61 |
62 $balanced_curlies # Hash dereference after '->'
63 )
64 )
65 |
66 $balanced_brackets # Array dereference
67 |
68 $balanced_curlies # Hash dereference
69 )*
70 )
71 /x;
72  
73  
74 178 my $variable_regex2 = qr/
75 (?<!\\) # Negative lookbehind for backslash
76 (?<variable> # Named capturing group 'variable'
77 \$
78 \w+ (?: :: \w+ )* # Variable name, possibly with package names
79 (?: # Non-capturing group for operators
80 (?:
81 -> # Dereference operator
82 (?:
83 \$? \w+ # Method name
84 (?: $balanced_parens )? # Optional method arguments
85 |
86 $balanced_brackets # Array dereference after '->'
87 |
88 $balanced_curlies # Hash dereference after '->'
89 )
90 )
91 |
92 $balanced_brackets # Array dereference
93 |
94 $balanced_curlies # Hash dereference
95 )*
96 )
97 /x;
98  
99 ## New Instance of the core template methods
100  
101 38 ▶sub raw { my ($self, @args) = @_; return Template::EmbeddedPerl::SafeString::raw(@args) }
Subroutine raw: called CC=1 SCAR=0.0
Pod documented
102 18 ▶sub safe { my ($self, @args) = @_; return Template::EmbeddedPerl::SafeString::safe(@args) }
Subroutine safe: called CC=1 SCAR=0.0
Pod documented
103 53 ▶sub safe_concat { my ($self, @args) = @_; return Template::EmbeddedPerl::SafeString::safe_concat(@args) }
Subroutine safe_concat: called CC=1 SCAR=0.0
Pod documented
104 17 ▶sub html_escape { my ($self, @args) = @_; return Template::EmbeddedPerl::SafeString::html_escape(@args) }
Subroutine html_escape: called CC=1 SCAR=0.0
Pod documented
105 17 ▶sub url_encode { my ($self, @args) = @_; return Template::EmbeddedPerl::Utils::uri_escape(@args) }
Subroutine url_encode: called CC=1 SCAR=0.0
Pod documented
106 17 ▶sub escape_javascript { my ($self, @args) = @_; return Template::EmbeddedPerl::Utils::escape_javascript(@args) }
Subroutine escape_javascript: called CC=1 SCAR=0.0
Pod documented
107  
108 30 ▶sub trim {
Subroutine trim: called CC=3 SCAR=11.0
Pod documented
109 17 my ($self, $string) = @_;
110 20 ▶ if ( (Scalar::Util::blessed($string)||'') eq 'Template::EmbeddedPerl::SafeString') {
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::blessed($string) || '') eq 'Template::EmbeddedPerl::SafeString') { } 1 2 3
Condition100%2/2
builtin::blessed($string) || ''
l!l
12
MC/DC100%1/1
builtin::blessed($string) || ''
builtin::blessed($string)
Truth table100%2/2
A
A= builtin::blessed($string)
Aresult
11
00
111 20 $string =~s/^[ \t]+|[ \t]+$//g;
112 20 return $self->raw($string);
113 } else {
114 20 $string =~s/^[ \t]+|[ \t]+$//g;
115 }
116 20 return $string;
117 }
118  
119 18 ▶sub mtrim {
Subroutine mtrim: called CC=3 SCAR=12.7
Pod documented
120 31 my ($self, $string) = @_;
121 31 ▶ if ( (Scalar::Util::blessed($string)||'') eq 'Template::EmbeddedPerl::SafeString') {
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::blessed($string) || '') eq 'Template::EmbeddedPerl::SafeString') { } 0 0 0
Condition0%0/2
builtin::blessed($string) || ''
l!l
00
MC/DC0%0/1
builtin::blessed($string) || ''
builtin::blessed($string)
Truth table0%0/2
A
A= builtin::blessed($string)
Aresult
11
00
122 19 $string =~s/^[ \t]+|[ \t]+$//mg;
123 19 return $self->raw($string);
124 } else {
125 40 $string =~s/^[ \t]+|[ \t]+$//mg;
126 }
127 40 return $string;
128 }
129  
130 35 ▶sub directory_for_package {
Subroutine directory_for_package: called CC=3 SCAR=13.0
Pod documented
131 67 my $self = shift;
132 67 ▶ my $class = ref($self) || $self;
Condition0%0/3
ref $self || $self
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table0%0/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
133 18 ▶ my $package = @_ ? shift(@_) : $class;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 0 0 0
134
135 18 $package =~ s/::/\//g;
136 67 my $path = $INC{"${package}.pm"};
137 67 my ($volume,$directories,$file) = File::Spec->splitpath( $path );
138  
139 67 return $directories;
140 }
141  
142 20 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
143 22 my $class = shift;
144 22 my (%args) = (
145 open_tag => '<%',
146 close_tag => '%>',
147 expr_marker => '=',
148 line_start => '%',
149 smart_lines => 0,
150 sandbox_ns => 'Template::EmbeddedPerl::Sandbox',
151 directories => [],
152 template_extension => 'epl',
153 auto_escape => 0,
154 auto_flatten_expr => 1,
155 prepend => '',
156 preamble => '',
157 use_cache => 0,
158 vars => 0,
159 comment_mark => '#',
160 interpolation => 0,
161 @_,
162 );
163  
164 52 ▶ %args = (%args, $class->config,) if $class->can('config');
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("config") 0 106 106
165  
166 52 my $self = bless \%args, $class;
167  
168 36 $self->inject_helpers;
169 35 return $self;
170 }
171  
172 20 ▶sub inject_helpers {
Subroutine inject_helpers: called CC=8 SCAR=20.8
Pod undocumented
173 35 my ($self) = @_;
174 35 my $sandbox_ns = $self->{sandbox_ns};
175 35 ▶ die "Invalid sandbox namespace '$sandbox_ns'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sandbox_ns and $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 1 105 106
Condition66%2/3
defined $sandbox_ns and $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
!ll&&!rl&&r
01105
MC/DC50%1/2
defined $sandbox_ns and $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
defined $sandbox_ns $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
Truth table66%2/3
A and B
A= defined $sandbox_nsB= $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
ABresult
0X0
100
111
176 unless defined($sandbox_ns) && $sandbox_ns =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
177  
178 19 my %helpers = $self->get_helpers;
179 19 foreach my $helper(keys %helpers) {
180 81 ▶ die "Invalid template helper name '$helper'"
Branch: 1 branch
BranchTrueFalseTotal
unless $helper =~ /\A[A-Za-z_]\w*\z/ 1 1700 1701
181 unless $helper =~ /\A[A-Za-z_]\w*\z/;
182  
183 81 ▶ if($self->{sandbox_ns}->can($helper)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"sandbox_ns"}->can($helper)) 1294 406 1700
184 warn "Skipping injection of helper '$helper'; already exists in namespace $self->{sandbox_ns}"
185 31 ▶ if $ENV{DEBUG_TEMPLATE_EMBEDDED_PERL};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"DEBUG_TEMPLATE_EMBEDDED_PERL"} 0 1294 1294
186 31 next;
187 }
188 65 ▶ eval qq[
Subroutine content_for: called CC=1 SCAR=0.0
Subroutine content_replace: called CC=1 SCAR=0.0
Subroutine display_heading: called CC=1 SCAR=0.0
Subroutine escape_javascript: called CC=1 SCAR=0.0
Subroutine has_content: called CC=1 SCAR=0.0
Subroutine html_escape: called CC=1 SCAR=0.0
Subroutine layout: called CC=1 SCAR=0.0
Subroutine mtrim: called CC=1 SCAR=0.0
Subroutine partial: called CC=1 SCAR=0.0
Subroutine raw: called CC=1 SCAR=0.0
Subroutine safe: called CC=1 SCAR=0.0
Subroutine safe_concat: called CC=1 SCAR=0.0
Subroutine to_safe_string: called CC=1 SCAR=0.0
Subroutine trim: called CC=1 SCAR=0.0
Subroutine url_encode: called CC=1 SCAR=0.0
Subroutine view: called CC=1 SCAR=0.0
Subroutine yield: called CC=1 SCAR=0.0
189 65 package @{[ $self->{sandbox_ns} ]};
190 sub $helper {
191 my \$context = Template::EmbeddedPerl->_current_render_context('$helper');
192 my \$engine = \$context->engine;
193 \$engine->get_helpers('$helper')->(\$engine, \@_);
194 }
195 65 ▶ ]; die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 406 406
196 }
197 }
198  
199 184 ▶sub _current_render_context {
Subroutine _current_render_context: called CC=2 SCAR=6.9
200 369 my ($class, $helper) = @_;
201 210 my $context = $ACTIVE_RENDERER;
202  
203 179 ▶ die "Template helper '$helper' called outside render context" unless $context;
Branch: 1 branch
BranchTrueFalseTotal
unless $context 6 1811 1817
204  
205 300 return $context;
206 }
207  
208 66 ▶sub _new_render_context {
Subroutine _new_render_context: called CC=1 SCAR=0.0
209 193 my ($self, %args) = @_;
210 70 return Template::EmbeddedPerl::RenderContext->new(
211 engine => $self,
212 frame => Template::EmbeddedPerl::RenderFrame->new,
213 %args,
214 );
215 }
216  
217 17 ▶sub render_view {
Subroutine render_view: called CC=2 SCAR=6.9
Pod documented
218 13 my ($self, $view) = @_;
219 15 ▶ die "render_view requires a blessed view object\n"
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($view) 3 13 16
220 unless Scalar::Util::blessed($view);
221  
222 14 my $context = $self->_new_render_context(
223 view => $view,
224 root_view => $view,
225 );
226 14 return $context->render_view_object($view);
227 }
228  
229 111 ▶sub get_helpers {
Subroutine get_helpers: called CC=4 SCAR=13.9
Pod documented
230 111 my ($self, $helper) = @_;
231 112 ▶ my %helpers = ($self->default_helpers, %{ $self->{helpers} || +{} });
Condition100%2/2
$self->{'helpers'} || {}
l!l
962312
MC/DC100%1/1
$self->{'helpers'} || {}
$self->{'helpers'}
Truth table100%2/2
A
A= $self->{'helpers'}
Aresult
11
00
232  
233 114 ▶ %helpers = (%helpers, $self->helpers) if $self->can('helpers');
Branch: 1 branch
BranchTrueFalseTotal
if $self->can("helpers") 0 1274 1274
234
235 173 ▶ return $helpers{$helper} if defined $helper;
Branch: 1 branch
BranchTrueFalseTotal
if defined $helper 1169 105 1274
236 77 return %helpers;
237 }
238  
239 111 ▶sub default_helpers {
Subroutine default_helpers: called CC=1 SCAR=0.0
Pod documented
240 139 my $self = shift;
241 return (
242 126 ▶ raw => sub { my ($self, @args) = @_; return $self->raw(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
243 118 ▶ safe => sub { my ($self, @args) = @_; return $self->safe(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
244 43 ▶ safe_concat => sub { my ($self, @args) = @_; return $self->safe_concat(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
245 8 ▶ html_escape => sub { my ($self, @args) = @_; return $self->html_escape(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
246 8 ▶ url_encode => sub { my ($self, @args) = @_; return $self->url_encode(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
247 60 ▶ escape_javascript => sub { my ($self, @args) = @_; return $self->escape_javascript(@args); },
Subroutine __ANON__: called CC=1 SCAR=0.0
248 82 ▶ trim => sub { my ($self, $arg) = @_; return $self->trim($arg); },
Subroutine __ANON__: called CC=1 SCAR=0.0
249 97 ▶ mtrim => sub { my ($self, $arg) = @_; return $self->mtrim($arg); },
Subroutine __ANON__: called CC=1 SCAR=0.0
250 27 ▶ partial => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
251 83 my ($engine, $identifier, @args) = @_;
252 107 my $context = Template::EmbeddedPerl->_current_render_context('partial');
253 74 my $output = $context->render_file('partial', $identifier, @args);
254 49 return $engine->raw($output);
255 },
256 40 ▶ view => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
257 47 my ($engine, $target, @args) = @_;
258 80 ▶ my $body = @args && ref($args[-1]) eq 'CODE' ? pop @args : undef;
Branch: 1 branch
BranchTrueFalseTotal
@args && ref $args[-1] eq 'CODE' ? : 17 51 68
Condition100%3/3
@args and ref $args[-1] eq "CODE"
!ll&&!rl&&r
272417
MC/DC100%2/2
@args and ref $args[-1] eq "CODE"
@args ref $args[-1] eq "CODE"
Truth table100%3/3
A and B
A= @argsB= ref $args[-1] eq "CODE"
ABresult
0X0
100
111
259 99 my $context = Template::EmbeddedPerl->_current_render_context('view');
260 40 ▶ my $output = $context->frame->with_transaction(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
261 258 my $child = $context->build_child_view($target, \@args);
262 258 ▶ my $captured = $body ? $body->($child) : '';
Branch: 1 branch
BranchTrueFalseTotal
$body ? : 17 35 52
263 return $context->frame->with_body(
264 defined($captured) ? $captured : '',
265 73 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
266 137 return $context->with(view => $child)->render_view_object($child);
267 },
268 137 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
defined $captured ? : 50 0 50
269 389 });
270 378 return $engine->raw($output);
271 },
272 46 ▶ layout => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
273 135 my ($engine, $identifier, @args) = @_;
274 56 my $context = Template::EmbeddedPerl->_current_render_context('layout');
275 56 $context->frame->register_layout($identifier, @args);
276 56 return;
277 },
278 20 ▶ content_for => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
279 36 my ($engine, @args) = @_;
280 67 my ($name, $callback) = _content_capture_arguments('content_for', @args);
281 65 my $frame = Template::EmbeddedPerl->_current_render_context('content_for')->frame;
282 64 my $output = $callback->();
283 64 ▶ $frame->append_content($name, $engine->raw(defined $output ? $output : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $output ? : 31 0 31
284 70 return;
285 },
286 69 ▶ content_replace => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
287 38 my ($engine, @args) = @_;
288 40 my ($name, $callback) = _content_capture_arguments('content_replace', @args);
289 284 my $frame = Template::EmbeddedPerl->_current_render_context('content_replace')->frame;
290 272 my $output = $callback->();
291 250 ▶ $frame->replace_content($name, $engine->raw(defined $output ? $output : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $output ? : 13 0 13
292 262 return;
293 },
294 27 ▶ has_content => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
295 65 my ($engine, @args) = @_;
296 52 my ($name) = _content_name_arguments('has_content', @args);
297 51 return Template::EmbeddedPerl->_current_render_context('has_content')->frame
298 ->has_content($name);
299 },
300 55 ▶ yield => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
301 42 my ($engine, @args) = @_;
302 42 my $frame = Template::EmbeddedPerl->_current_render_context('yield')->frame;
303 20 ▶ my $output = @args
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 34 45 79
304 ? $frame->content(_content_name_arguments('yield', @args))
305 : $frame->default_body;
306 64 return $engine->raw($output);
307 },
308 48 ▶ to_safe_string => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
309 94 my ($engine, @args) = @_;
310 94 my $context = Template::EmbeddedPerl->_current_render_context('to_safe_string');
311 137 ▶ my $receiver = defined($context->view) ? $context->view : $engine;
Branch: 1 branch
BranchTrueFalseTotal
defined $context->view ? : 151 196 347
312 return map {
313 118 ▶ Scalar::Util::blessed($_) && $_->can('to_safe_string')
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_) && $_->can('to_safe_string') ? : 4 333 337
Condition100%3/3
builtin::blessed($_) and $_->can("to_safe_string")
!ll&&!rl&&r
2181154
MC/DC100%2/2
builtin::blessed($_) and $_->can("to_safe_string")
builtin::blessed($_) $_->can("to_safe_string")
Truth table100%3/3
A and B
A= builtin::blessed($_)B= $_->can("to_safe_string")
ABresult
0X0
100
111
314 ? $_->to_safe_string($receiver)
315 : $_;
316 } @args;
317 },
318 138 );
319 }
320  
321 58 ▶sub _content_capture_arguments {
Subroutine _content_capture_arguments: called CC=6 SCAR=18.0
322 27 my ($helper, @args) = @_;
323 29 ▶ die "Invalid $helper arguments" unless @args == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @args == 2 0 49 49
324 76 my ($name, $callback) = @args;
325 62 ▶ die "Invalid $helper name" unless defined($name) && !ref($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and length $name 3 46 49
Condition83%5/6
defined $name and not ref $name and length $name
!ll&&!rl&&r
1246
defined $name and not ref $name
!ll&&!rl&&r
1048
MC/DC66%2/3
defined $name and not ref $name and length $name
defined $name not ref $name length $name
Truth table75%3/4
A and not(B) and C
A= defined $nameB= not ref $nameC= length $name
ABCresult
0XX0
10X0
1100
1111
326 73 ▶ die "Invalid $helper callback" unless ref($callback) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 1 45 46
327 73 return ($name, $callback);
328 }
329  
330 87 ▶sub _content_name_arguments {
Subroutine _content_name_arguments: called CC=5 SCAR=17.0
331 176 my ($helper, @args) = @_;
332 176 ▶ die "Invalid $helper arguments" unless @args == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @args == 1 0 47 47
333 180 my ($name) = @args;
334 150 ▶ die "Invalid $helper name" unless defined($name) && !ref($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and length $name 2 45 47
Condition50%3/6
defined $name and not ref $name and length $name
!ll&&!rl&&r
0245
defined $name and not ref $name
!ll&&!rl&&r
0047
MC/DC33%1/3
defined $name and not ref $name and length $name
defined $name not ref $name length $name
Truth table50%2/4
A and not(B) and C
A= defined $nameB= not ref $nameC= length $name
ABCresult
0XX0
10X0
1100
1111
335 176 return $name;
336 }
337  
338 # Create a new template document in various ways
339  
340 32 ▶sub from_string {
Subroutine from_string: called CC=7 SCAR=19.5
Pod documented
341 183 my ($proto, $template, %args) = @_;
342 43 my $source = delete($args{source});
343 61 my $identifier = delete($args{identifier});
344 52 ▶ my $self = ref($proto) ? $proto : $proto->new(%args);
Branch: 1 branch
BranchTrueFalseTotal
ref $proto ? : 377 7 384
345 39 my $diagnostic_source = diagnostic_source_label($source);
346  
347 52 my $digest;
348 51 ▶ if($self->{use_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"use_cache"}) 49 335 384
349 40 ▶ $self->{compiled_cache} ||= {};
Condition100%2/2
$self->{"compiled_cache"} ||= {}
l!l
3910
MC/DC100%1/1
$self->{"compiled_cache"} ||= {}
$self->{"compiled_cache"}
Truth table100%2/2
A
A= $self->{"compiled_cache"}
Aresult
11
00
350 42 $digest = Digest::MD5::md5_hex(
351 $template,
352 "\0template-source\0",
353 encode('UTF-8', $diagnostic_source),
354 );
355 42 ▶ if(my $cached = $self->{compiled_cache}->{$digest}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"compiled_cache"}{$digest}) 20 29 49
356 return bless {
357 template => $cached->{template},
358 parsed => $cached->{parsed},
359 code => $cached->{code},
360 60 yat => $self,
361 source => $source,
362 identifier => $identifier,
363 }, 'Template::EmbeddedPerl::Compiled';
364 }
365 }
366  
367 72 $template = normalize_linefeeds($template);
368  
369 71 my @template = split(/\n/, $template);
370 815 my ($rewritten_template) = eval {
371 Template::EmbeddedPerl::Arguments->rewrite(
372 $template,
373 comment_mark => $self->{comment_mark},
374 line_start => $self->{line_start},
375 open_tag => $self->{open_tag},
376 close_tag => $self->{close_tag},
377 814 );
378 };
379 815 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 16 348 364
380 798 my $error = $@;
381 118 $error =~ s/ at template line (\d+)\n\z/ at $diagnostic_source line $1\n/;
382 139 die $error;
383 }
384  
385 58 my @parsed = $self->parse_template($rewritten_template);
386 37 my $code = $self->compile(\@template, $source, @parsed);
387  
388 29 ▶ if($self->{use_cache}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"use_cache"}) 29 308 337
389 44 $self->{compiled_cache}->{$digest} = {
390 template => \@template,
391 parsed => \@parsed,
392 code => $code,
393 };
394 }
395  
396 556 return bless {
397 template => \@template,
398 parsed => \@parsed,
399 code => $code,
400 yat => $self,
401 source => $source,
402 identifier => $identifier,
403 }, 'Template::EmbeddedPerl::Compiled';
404 }
405  
406 54 ▶sub from_data {
Subroutine from_data: called CC=9 SCAR=23.4
Pod documented
407 547 my ($proto, $package, @args) = @_;
408  
409 527 ▶ die "Invalid package name '$package'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $package and $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 0 5 5
Condition33%1/3
defined $package and $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
!ll&&!rl&&r
005
MC/DC0%0/2
defined $package and $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
defined $package $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
Truth table33%1/3
A and B
A= defined $packageB= $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
ABresult
0X0
100
111
410 unless defined($package) && $package =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
411  
412 527 my $package_file = $package;
413 526 $package_file =~ s{::}{/}g;
414 26 ▶ eval { require "${package_file}.pm"; 1 }; if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5 5
415 117 die "Failed to load package '$package': $@";
416 }
417  
418 26 ▶ my $data_handle = do { no strict 'refs'; *{"${package}::DATA"}{IO} };
Subroutine BEGIN: called CC=1 SCAR=0.0
419 176 ▶ if (defined $data_handle) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data_handle) { } 4 1 5
420 9 my $position = tell($data_handle);
421 9 my $data_content = do { local $/; <$data_handle> };
422 18 ▶ seek($data_handle, $position, 0)
Branch: 1 branch
BranchTrueFalseTotal
if defined $position and $position >= 0 4 0 4
Condition37%3/8
defined $position && $position >= 0 && (seek($data_handle, $position, 0) || die("Failed to restore __DATA__ handle for package '${package}': $!"))
!ll&&!rl&&r
040
defined $position and $position >= 0
!ll&&!rl&&r
004
seek $data_handle, $position, 0 or die "Failed to restore __DATA__ handle for package '${package}': $!"
l!l
40
MC/DC0%0/3
defined $position && $position >= 0 && (seek($data_handle, $position, 0) || die("Failed to restore __DATA__ handle for package '${package}': $!"))
defined $position $position >= 0 seek $data_handle, $position, 0
Truth table0%0/4
A and B && C
A= defined $positionB= $position >= 0C= seek $data_handle, $position, 0
ABCresult
0XX0
10X0
1100
1111
423 or die "Failed to restore __DATA__ handle for package '$package': $!"
424 if defined($position) && $position >= 0;
425 13 my $path = $INC{"${package_file}.pm"};
426 20 ▶ return $proto->from_string($data_content, @args, source => "@{[ $path || $package ]}/DATA");
Condition33%1/3
$path || $package
l!l&&r!l&&!r
400
MC/DC0%0/2
$path || $package
$path $package
Truth table33%1/3
A || B
A= $pathB= $package
ABresult
1X1
011
000
427 } else {
428 19 die "No __DATA__ section found in package '$package'";
429 }
430 }
431  
432 177 ▶sub from_fh {
Subroutine from_fh: called CC=1 SCAR=0.0
Pod documented
433 38 my ($proto, $fh, @args) = @_;
434 57 my $data = do { local $/; <$fh> };
435 56 close $fh;
436  
437 62 return $proto->from_string($data, @args);
438 }
439  
440 199 ▶sub from_file {
Subroutine from_file: called CC=3 SCAR=11.0
Pod documented
441 246 my ($proto, $file_proto, @args) = @_;
442 250 ▶ my $self = ref($proto) ? $proto : $proto->new(@args);
Branch: 1 branch
BranchTrueFalseTotal
ref $proto ? : 140 1 141
443 250 my $path = $self->_resolve_template_file($file_proto);
444 241 ▶ $Template::EmbeddedPerl::RenderContext::SOURCE_OBSERVER->($self, $file_proto, $path)
Branch: 1 branch
BranchTrueFalseTotal
if $Template::EmbeddedPerl::RenderContext::SOURCE_OBSERVER 119 14 133
445 if $Template::EmbeddedPerl::RenderContext::SOURCE_OBSERVER;
446 73 return $self->_from_resolved_file($file_proto, $path, @args);
447 }
448  
449 33 ▶sub _from_resolved_file {
Subroutine _from_resolved_file: called CC=2 SCAR=7.0
450 73 my ($self, $identifier, $path, @args) = @_;
451 89 ▶ open my $fh, '<', $path or die "Failed to open file $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or die "Failed to open file ${path}: $!" 133 0 133
452 89 my %args = (@args, source => $path, identifier => $identifier);
453 97 return $self->from_fh($fh, %args);
454 }
455  
456 38 ▶sub _template_candidates {
Subroutine _template_candidates: called CC=2 SCAR=6.9
457 90 my ($self, $identifier) = @_;
458 233 my $file = "$identifier.$self->{template_extension}";
459 return map {
460 196 ▶ File::Spec->catfile(ref($_) eq 'ARRAY' ? File::Spec->catdir(@$_) : $_, $file)
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 13 153 166
461 232 } @{ $self->{directories} };
462 }
463  
464 51 ▶sub _resolve_template_file {
Subroutine _resolve_template_file: called CC=2 SCAR=6.9
465 198 my ($self, $identifier) = @_;
466 53 my @candidates = $self->_template_candidates($identifier);
467 195 return $_ for grep { -e $_ } @candidates;
468 53 die "Template '$identifier' not found; searched: " . join(', ', @candidates) . "\n";
469 }
470  
471 73 ▶sub _snake_case_segment {
Subroutine _snake_case_segment: called CC=1 SCAR=0.0
472 57 my ($self, $segment) = @_;
473 51 $segment =~ s/([A-Z]+)([A-Z][a-z])/$1_$2/g;
474 63 $segment =~ s/([a-z0-9])([A-Z])/$1_$2/g;
475 112 return lc $segment;
476 }
477  
478 823 ▶sub _class_to_template {
Subroutine _class_to_template: called CC=5 SCAR=16.4
479 110 my ($self, $class) = @_;
480 147 my $namespace = $self->{view_namespace};
481 147 ▶ my $prefix = defined($namespace) ? "$namespace\::" : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $namespace ? : 50 0 50
482  
483 146 ▶ die "Cannot resolve template for view class '$class'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $prefix and index($class, $prefix) == 0 2 48 50
Condition66%2/3
defined $prefix and index($class, $prefix) == 0
!ll&&!rl&&r
0248
MC/DC50%1/2
defined $prefix and index($class, $prefix) == 0
defined $prefix index($class, $prefix) == 0
Truth table66%2/3
A and B
A= defined $prefixB= index($class, $prefix) == 0
ABresult
0X0
100
111
484 unless defined($prefix) && index($class, $prefix) == 0;
485  
486 185 my $suffix = substr($class, length($prefix));
487 90 ▶ die "Cannot resolve template for view class '$class'\n" unless length($suffix);
Branch: 1 branch
BranchTrueFalseTotal
unless length $suffix 0 48 48
488  
489 90 return join '/', map { $self->_snake_case_segment($_) } split /::/, $suffix;
490 }
491  
492 140 ▶sub _logical_view_class {
Subroutine _logical_view_class: called CC=7 SCAR=20.4
493 157 my ($self, $logical_name) = @_;
494  
495 157 ▶ die "Invalid logical view name '$logical_name'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $logical_name and not ref $logical_name and $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 1 39 40
Condition50%3/6
defined $logical_name and not ref $logical_name and $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
!ll&&!rl&&r
0139
defined $logical_name and not ref $logical_name
!ll&&!rl&&r
0040
MC/DC33%1/3
defined $logical_name and not ref $logical_name and $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
defined $logical_name not ref $logical_name $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
Truth table50%2/4
A and not(B) and C
A= defined $logical_nameB= not ref $logical_nameC= $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
ABCresult
0XX0
10X0
1100
1111
496 unless defined($logical_name)
497 && !ref($logical_name)
498 && $logical_name =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
499  
500 135 my $namespace = $self->{view_namespace};
501 210 ▶ die "Logical view '$logical_name' requires view_namespace\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $namespace and length $namespace 1 38 39
Condition66%2/3
defined $namespace and length $namespace
!ll&&!rl&&r
1038
MC/DC50%1/2
defined $namespace and length $namespace
defined $namespace length $namespace
Truth table66%2/3
A and B
A= defined $namespaceB= length $namespace
ABresult
0X0
100
111
502 unless defined($namespace) && length($namespace);
503 218 ▶ die "Invalid view_namespace '$namespace'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $namespace =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 0 38 38
504 unless $namespace =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
505  
506 158 return "$namespace\::$logical_name";
507 }
508  
509 53 ▶sub _construct_view {
Subroutine _construct_view: called CC=11 SCAR=24.0
510 162 my ($self, $logical_name, $args, $context) = @_;
511 166 my $class = $self->_logical_view_class($logical_name);
512  
513 73 ▶ unless ($class->can('new')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("new")) 8 30 38
514 162 my $class_file = "$class.pm";
515 137 $class_file =~ s{::}{/}g;
516 54 my $loaded = eval { require $class_file; 1 };
517 54 ▶ die "Failed to load logical view '$logical_name' as '$class': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless $loaded 1 7 8
518 unless $loaded;
519 }
520  
521 91 my $factory = $self->{view_factory};
522 192 ▶ die "view_factory must be a code reference\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $factory and ref $factory ne "CODE" 1 36 37
Condition100%3/3
defined $factory and ref $factory ne "CODE"
!ll&&!rl&&r
7291
MC/DC100%2/2
defined $factory and ref $factory ne "CODE"
defined $factory ref $factory ne "CODE"
Truth table100%3/3
A and B
A= defined $factoryB= ref $factory ne "CODE"
ABresult
0X0
100
111
523 if defined($factory) && ref($factory) ne 'CODE';
524  
525 171 my $view;
526 172 ▶ if ($factory) {
Branch: 1 branch
BranchTrueFalseTotal
if ($factory) { } 29 7 36
527 172 my $constructed = eval {
528 158 $view = $factory->($class, {%$args}, $context);
529 158 1;
530 };
531 158 ▶ die "view_factory failed for logical view '$logical_name' as '$class': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless $constructed 2 27 29
532 unless $constructed;
533 } else {
534 46 my $constructed = eval {
535 46 $view = $class->new(%$args);
536 45 1;
537 };
538 22 ▶ die "Failed to construct logical view '$logical_name' as '$class': $@"
Branch: 1 branch
BranchTrueFalseTotal
unless $constructed 2 5 7
539 unless $constructed;
540 }
541  
542 161 ▶ die "view_factory did not return a blessed view for '$logical_name'\n"
Branch: 1 branch
BranchTrueFalseTotal
if $factory and not builtin::blessed($view) 1 31 32
Condition100%3/3
$factory and not builtin::blessed($view)
!ll&&!rl&&r
5261
MC/DC100%2/2
$factory and not builtin::blessed($view)
$factory not builtin::blessed($view)
Truth table100%3/3
A and not(B)
A= $factoryB= not builtin::blessed($view)
ABresult
0X0
100
111
543 if $factory && !Scalar::Util::blessed($view);
544 149 ▶ die "Constructor did not return a blessed view for '$logical_name'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($view) 0 31 31
545 unless Scalar::Util::blessed($view);
546  
547 151 return $view;
548 }
549  
550 563 ▶sub _resolve_view_template {
Subroutine _resolve_view_template: called CC=7 SCAR=20.8
551 151 my ($self, $view) = @_;
552 150 ▶ my $class = Scalar::Util::blessed($view) || ref($view) || "$view";
Condition33%2/6
builtin::blessed($view) || ref $view || "$view"
l!l&&r!l&&!r
6700
builtin::blessed($view) or ref $view
l!l&&r!l&&!r
6700
MC/DC0%0/3
builtin::blessed($view) || ref $view || "$view"
builtin::blessed($view) ref $view "$view"
Truth table25%1/4
A or B || C
A= builtin::blessed($view)B= ref $viewC= "$view"
ABCresult
1XX1
01X1
0011
0000
553  
554 40 ▶ if (Scalar::Util::blessed($view) && $view->can('template')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($view) and $view->can("template")) 23 44 67
Condition66%2/3
builtin::blessed($view) and $view->can("template")
!ll&&!rl&&r
04423
MC/DC50%1/2
builtin::blessed($view) and $view->can("template")
builtin::blessed($view) $view->can("template")
Truth table66%2/3
A and B
A= builtin::blessed($view)B= $view->can("template")
ABresult
0X0
100
111
555 37 my $template = $view->template;
556 37 ▶ return $template if defined($template) && length($template);
Branch: 1 branch
BranchTrueFalseTotal
if defined $template and length $template 22 1 23
Condition66%2/3
defined $template and length $template
!ll&&!rl&&r
0122
MC/DC50%1/2
defined $template and length $template
defined $template length $template
Truth table66%2/3
A and B
A= defined $templateB= length $template
ABresult
0X0
100
111
557 }
558  
559 143 return $self->_class_to_template($class);
560 }
561  
562 # Methods to parse and compile the template
563  
564 567 ▶sub parse_template {
Subroutine parse_template: called CC=18 SCAR=28.9
Pod documented
565 149 my ($self, $template) = @_;
566 157 my $open_tag = $self->{open_tag};
567 61 my $close_tag = $self->{close_tag};
568 193 my $expr_marker = $self->{expr_marker};
569 125 my $line_start = $self->{line_start};
570 121 my $comment_mark = $self->{comment_mark};
571 98 my $trim_close_tag = "-${close_tag}";
572 73 my $expr_trim_close_tag = "${expr_marker}${close_tag}";
573  
574 ## support shorthand line start tags ##
575  
576 30 ▶ if ($self->{smart_lines}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'smart_lines'}) { } 166 182 348
577 33 $template =~ s{\r\n}{\n}g;
578 37 $template =~ s{
579 ^[\t ]*\Q${line_start}${expr_marker}\E(.*?)(\n|\z)
580 }{
581 65 ▶ $open_tag . $expr_marker . $1 . $close_tag
Branch: 1 branch
BranchTrueFalseTotal
length $2 ? : 50 1 51
582 . (length($2) ? "\\\n" : '')
583 }mgex;
584 62 $template =~ s{
585 ^[\t ]*(?!\Q${close_tag}\E[\t ]*$)\Q${line_start}\E(.*?)(\n|\z)
586 }{
587 77 ▶ $open_tag . $1 . $close_tag
Branch: 1 branch
BranchTrueFalseTotal
length $2 ? : 124 0 124
588 . (length($2) ? "\\\n" : '')
589 }mgex;
590 } else {
591 # Convert all lines starting with %= to start with <%= and then add %> to the end
592 67 $template =~ s{^\s*\Q${line_start}${expr_marker}\E(.*?)(?=\\?$)}{${open_tag}${expr_marker}$1${close_tag}}mg;
593 # Convert all lines starting with % to start with <% and then add %> to the end
594 # Exclude lines containing only the closing tag from conversion.
595 56 $template =~ s{^\s*(?!\Q${close_tag}\E\s*\\?$)\Q${line_start}\E(.*?)(?=\\?$)}{${open_tag}$1${close_tag}}mg;
596 }
597  
598 ## Escapes so you can actually have % and %= in the template
599 # Convert all lines starting with \%= to start instead with %=
600 64 $template =~ s{^\s*\\\Q${line_start}${expr_marker}\E(.*)$}{${line_start}${expr_marker}$1}mg;
601 # Convert all lines starting with \% to start instead with %
602 67 $template =~ s{^\s*\\\Q${line_start}\E(.*)$}{${line_start}$1}mg;
603  
604 # This code parses the template and returns an array of parsed blocks.
605 # Each block is represented as an array reference with two elements: the type and the content.
606 # The type can be 'expr' for expressions enclosed in double square brackets,
607 # 'code' for code blocks enclosed in double square brackets,
608 # or 'text' for plain text blocks.
609 # The content is the actual content of the block, trimmed of leading and trailing whitespace.
610  
611 #my @segments = split /(\Q${open_tag}\E.*?\Q${close_tag}\E)/s, $template;
612 49 my @segments = split /((?<!\\)\Q${open_tag}\E.*?(?<!\\)\Q${close_tag}\E)/s, $template;
613 63 my @parsed = ();
614 43 my $trim_next_text = 0;
615  
616 42 foreach my $segment (@segments) {
617  
618 117 my ($open_type, $content, $close_type) = ($segment =~ /^(\Q${open_tag}${expr_marker}\E|\Q$open_tag\E)(.*?)(\Q${trim_close_tag}\E|\Q${expr_trim_close_tag}\E|\Q$close_tag\E)?$/s);
619 128 ▶ if(!$open_type) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $open_type) { } 1006 719 1725
620 102 ▶ if($trim_next_text) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trim_next_text) 63 943 1006
621 59 $trim_next_text = 0;
622 100 ▶ if($segment =~ s/\A[ \t]*\n//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($segment =~ s/\A[ \t]*\n//) { } 61 2 63
623 109 $segment = "\\\n$segment";
624 } else {
625 109 $segment =~ s/\A[ \t]*\z//;
626 }
627 }
628  
629 # Remove \ from escaped line_start, open_tag, and close_tag
630 142 $segment =~ s{\\\Q${line_start}\E}{${line_start}}g;
631 153 $segment =~ s{\\\Q${open_tag}\E}{${open_tag}}g;
632 154 $segment =~ s{\\\Q${close_tag}\E}{${close_tag}}g;
633 188 $segment =~ s{\\\Q${expr_marker}${close_tag}\E}{${expr_marker}${close_tag}}g;
634  
635 # check the segment for comment lines
636 184 $segment =~ s{^[ \t]*?\Q${comment_mark}\E.*?(\\?)$}{$1}mg;
637 189 $segment =~ s{^[ \t]*?\\\Q${comment_mark}\E}{${comment_mark}}mg;
638  
639 175 ▶ if($self->{interpolation}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'interpolation'}) { } 55 951 1006
640 144 my @parts = ();
641 131 my $pos = 0;
642  
643 149 ▶ while ($segment =~ /$variable_regex/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($segment =~ /$variable_regex/g) 42 55 97
644  
645 149 my $match_start = $-[0];
646 191 my $match_end = $+[0];
647 169 my $matched_var = $+{variable};
648  
649 # Add non-matching part before the match
650 170 ▶ if ($match_start > $pos) {
Branch: 1 branch
BranchTrueFalseTotal
if ($match_start > $pos) 40 2 42
651 685 my $text = substr($segment, $pos, $match_start - $pos);
652 675 $text =~ s/\\\$/\$/gm; # Any escaped $ (\$) should be unescaped
653 655 push @parts, ['text', $text ];
654 }
655  
656 # Add the matching variable
657 648 push @parts, ['expr', $matched_var ];
658  
659 131 $pos = $match_end;
660 }
661 # Add any remaining non-matching part
662 131 ▶ if ($pos < length($segment)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < length $segment) 54 1 55
663 130 my $text = substr($segment, $pos);
664 38 $text =~ s/\\\$/\$/gm; # Any escaped $ (\$) should be unescaped
665 63 push @parts, [ 'text', $text ];
666 }
667 66 push @parsed, @parts;
668 } else {
669 127 push @parsed, ['text', $segment];
670 }
671 } else {
672 114 ▶ $trim_next_text = 0 if $trim_next_text;
Branch: 1 branch
BranchTrueFalseTotal
if $trim_next_text 0 719 719
673  
674 # Support trim with =%>
675 128 ▶ $content = "trim $content"
Branch: 1 branch
BranchTrueFalseTotal
if $open_type eq "$open_tag$expr_marker" and $close_type eq $expr_trim_close_tag 1 718 719
Condition100%3/3
$open_type eq "$open_tag$expr_marker" and $close_type eq $expr_trim_close_tag
!ll&&!rl&&r
3044141
MC/DC100%2/2
$open_type eq "$open_tag$expr_marker" and $close_type eq $expr_trim_close_tag
$open_type eq "$open_tag$expr_marker" $close_type eq $expr_trim_close_tag
Truth table100%3/3
A and B
A= $open_type eq "$open_tag$expr_marker"B= $close_type eq $expr_trim_close_tag
ABresult
0X0
100
111
676 if $open_type eq "${open_tag}${expr_marker}" && $close_type eq $expr_trim_close_tag;
677 153 ▶ $trim_next_text = 1 if $close_type eq $trim_close_tag;
Branch: 1 branch
BranchTrueFalseTotal
if $close_type eq $trim_close_tag 63 656 719
678  
679 # ?? ==%> or maybe something else...
680 # $parsed[-1][1] =~s/[ \t]+$//mg if $close_type eq "${expr_marker}${close_tag}";
681
682 # Remove \ from escaped line_start, open_tag, and close_tag
683 127 $content =~ s{\\\Q${line_start}\E}{${line_start}}g;
684 129 $content =~ s{\\\Q${open_tag}\E}{${open_tag}}g;
685 138 $content =~ s{\\\Q${close_tag}\E}{${close_tag}}g;
686 138 $content =~ s{\\\Q${expr_marker}${close_tag}\E}{${expr_marker}${close_tag}}g;
687  
688 93 ▶ if ($open_type eq "${open_tag}${expr_marker}") {
Branch: 2 branches
BranchTrueFalseTotal
if ($open_type eq "$open_tag$expr_marker") { } 415 304 719
elsif ($open_type eq $open_tag) { } 304 0 304
689 113 push @parsed, ['expr', tokenize($content)];
690 } elsif ($open_type eq $open_tag) {
691 73 push @parsed, ['code', tokenize($content)];
692 }
693 }
694 }
695  
696 67 return @parsed;
697 }
698  
699 97 ▶sub compile {
Subroutine compile: called CC=11 SCAR=24.0
Pod documented
700 42 my ($self, $template, $source, @parsed) = @_;
701  
702 59 my $compiled = '';
703 41 my $safe_or_not = '';
704 42 my $flatten_or_not = '';
705  
706 63 ▶ if($self->{auto_escape} && $self->{auto_flatten_expr}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'auto_escape'} and $self->{'auto_flatten_expr'}) { } 127 221 348
Condition66%2/3
$self->{"auto_escape"} and $self->{"auto_flatten_expr"}
!ll&&!rl&&r
2210127
MC/DC50%1/2
$self->{"auto_escape"} and $self->{"auto_flatten_expr"}
$self->{"auto_escape"} $self->{"auto_flatten_expr"}
Truth table66%2/3
A and B
A= $self->{"auto_escape"}B= $self->{"auto_flatten_expr"}
ABresult
0X0
100
111
707 109 $safe_or_not = ' safe_concat to_safe_string ';
708 } else {
709 126 ▶ $safe_or_not = $self->{auto_escape} ? ' safe to_safe_string ' : '';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'auto_escape'} ? : 0 221 221
710 104 ▶ $flatten_or_not = $self->{auto_flatten_expr} ? ' join "", ' : '';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'auto_flatten_expr'} ? : 221 0 221
711 }
712  
713 112 for my $block (@parsed) {
714 172 ▶ next if $block eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $block eq "" 0 1806 1806
715 170 my ($type, $content, $has_unmatched_open, $has_unmatched_closed) = @$block;
716  
717 175 ▶ if ($type eq 'expr') { # [[= ... ]]
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'expr') { } 457 1349 1806
elsif ($type eq 'code') { } 304 1045 1349
718 99 $compiled .= '$_O .= ' . $flatten_or_not . $safe_or_not . $content . ";";
719 } elsif ($type eq 'code') { # [[ ... ]]
720 88 $compiled .= $content . ";";
721 } else {
722 # if \\n is present in the content, replace it with ''
723 127 my $escaped_newline_start = $content =~ s/^\\\n//mg;
724 102 my $escaped_newline_end = $content =~ s/\\\n$//mg;
725  
726 112 $content =~ s/^\\\\/\\/mg;
727 118 $compiled .= ("\n" x $escaped_newline_start)
728 . ' $_O .= "' . quotemeta($content) . '";'
729 . ("\n" x $escaped_newline_end);
730 }
731 }
732  
733 88 $compiled = $self->compiled($compiled, $source);
734  
735 65 ▶ warn "Compiled: $compiled\n" if $ENV{DEBUG_TEMPLATE_EMBEDDED_PERL};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"DEBUG_TEMPLATE_EMBEDDED_PERL"} 0 348 348
736  
737 26 ▶ my $code = eval $compiled; if($@) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 11 337 348
738 100 die generate_error_message($@, $template, $source);
739 }
740  
741 122 return $code;
742 }
743  
744 64 ▶sub compiled {
Subroutine compiled: called CC=1 SCAR=0.0
Pod undocumented
745 93 my ($self, $compiled, $source) = @_;
746 106 my $diagnostic_source = diagnostic_source_label($source);
747 176 my $wrapper = "package @{[ $self->{sandbox_ns} ]}; ";
748 194 $wrapper .= "use strict; use warnings; use utf8; @{[ $self->{preamble} ]}; ";
749 106 $wrapper .= "sub { my \$__context = shift; my \$_O = ''; my \$self = \$__context->view; @{[ $self->{prepend} ]};\n";
750 209 $wrapper .= qq{#line 1 "$diagnostic_source"\n};
751 295 $wrapper .= "${compiled}; return \$_O; };";
752 380 return $wrapper;
753 }
754  
755 220 ▶sub tokenize {
Subroutine tokenize: called CC=1 SCAR=0.0
Pod undocumented
756 411 my $content = shift;
757 288 my $document = PPI::Document->new(\$content);
758 280 my ($has_unmatched_open, $has_unmatched_closed) = mark_unclosed_blocks($document);
759 283 return ($document, $has_unmatched_open, $has_unmatched_closed);
760 }
761  
762 45 ▶sub mark_unclosed_blocks {
Subroutine mark_unclosed_blocks: called CC=1 SCAR=0.0
Pod undocumented
763 263 my ($element) = @_;
764 226 my $blocks = $element->find('PPI::Structure::Block');
765 235 my $has_unmatched_open = mark_unclosed_open_blocks($element);
766 203 my $has_unmatched_closed = mark_unmatched_close_blocks($element);
767  
768 169 return ($has_unmatched_open, $has_unmatched_closed);
769 }
770  
771 22 ▶sub is_control_block {
Subroutine is_control_block: called CC=7 SCAR=20.2
Pod undocumented
772 187 my ($block) = @_;
773  
774 # Get the parent of the block
775 141 my $parent = $block->parent;
776  
777 # Check if the parent is a control statement
778 205 ▶ if ($parent && ($parent->isa('PPI::Statement::Compound') || $parent->isa('PPI::Statement'))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parent and $parent->isa("PPI::Statement::Compound") || $parent->isa("PPI::Statement")) 66 0 66
Condition50%3/6
$parent and $parent->isa("PPI::Statement::Compound") || $parent->isa("PPI::Statement")
!ll&&!rl&&r
0066
$parent->isa("PPI::Statement::Compound") or $parent->isa("PPI::Statement")
l!l&&r!l&&!r
25410
MC/DC0%0/3
$parent and $parent->isa("PPI::Statement::Compound") || $parent->isa("PPI::Statement")
$parent $parent->isa("PPI::Statement::Compound") $parent->isa("PPI::Statement")
Truth table50%2/4
A and B or C
A= $parentB= $parent->isa("PPI::Statement::Compound")C= $parent->isa("PPI::Statement")
ABCresult
0XX0
1000
11X1
1011
779 156 my $keyword = $parent->schild(0); # Get the first child of the statement, which should be the control keyword
780 104 ▶ if ($keyword && $keyword->isa('PPI::Token::Word')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keyword and $keyword->isa("PPI::Token::Word")) 64 2 66
Condition66%2/3
$keyword and $keyword->isa("PPI::Token::Word")
!ll&&!rl&&r
0264
MC/DC50%1/2
$keyword and $keyword->isa("PPI::Token::Word")
$keyword $keyword->isa("PPI::Token::Word")
Truth table66%2/3
A and B
A= $keywordB= $keyword->isa("PPI::Token::Word")
ABresult
0X0
100
111
781 # Check if the keyword is a control structure keyword
782 103 ▶ return 1 if $keyword->content =~ /^(if|else|elsif|while|for|foreach|unless|given|when|until)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $keyword->content =~ /^(if|else|elsif|while|for|foreach|unless|given|when|until)$/ 31 33 64
783 }
784 }
785  
786 176 return 0;
787 }
788  
789 58 ▶sub mark_unclosed_open_blocks {
Subroutine mark_unclosed_open_blocks: called CC=6 SCAR=17.9
Pod undocumented
790 244 my ($element, $level) = @_;
791 252 my $blocks = $element->find('PPI::Structure::Block');
792 267 ▶ return unless $blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless $blocks 602 117 719
793  
794 191 my $has_unmatched_open = 0;
795 191 foreach my $block (@$blocks) {
796 731 ▶ next if $block->finish; # Skip if closed
Branch: 1 branch
BranchTrueFalseTotal
if $block->finish 65 66 131
797 789 ▶ next if is_control_block($block);
Branch: 1 branch
BranchTrueFalseTotal
if is_control_block($block) 31 35 66
798 447 $has_unmatched_open = 1;
799
800 93 ▶ my @children = @{$block->{children}||[]};
Condition50%1/2
$block->{'children'} || []
l!l
350
MC/DC0%0/1
$block->{'children'} || []
$block->{'children'}
Truth table50%1/2
A
A= $block->{'children'}
Aresult
11
00
801 $block->{children} = [
802 94 bless({ content => " " }, 'PPI::Token::Whitespace'),
803 bless({
804 children => [
805 bless({ content => " " }, 'PPI::Token::Whitespace'),
806 bless({
807 children => [
808 bless({ content => "my" }, 'PPI::Token::Word'),
809 bless({ content => " " }, 'PPI::Token::Whitespace'),
810 bless({ content => "\$_O" }, 'PPI::Token::Symbol'),
811 bless({ content => "=" }, 'PPI::Token::Operator'),
812 bless({ content => "\"\"", separator => "\"" }, 'PPI::Token::Quote::Double'),
813 ],
814 }, 'PPI::Statement::Variable'),
815 @children,
816 ],
817 }, 'PPI::Statement'),
818 ];
819 }
820 58 return $has_unmatched_open;
821 }
822  
823 68 ▶sub mark_unmatched_close_blocks {
Subroutine mark_unmatched_close_blocks: called CC=5 SCAR=16.1
Pod undocumented
824 473 my ($element, $level) = @_;
825 511 my $blocks = $element->find('PPI::Statement::UnmatchedBrace');
826 511 ▶ return unless $blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless $blocks 653 66 719
827  
828 410 foreach my $block (@$blocks) {
829 431 ▶ next if $block eq ')'; # we only care about }
Branch: 1 branch
BranchTrueFalseTotal
if $block eq ")" 4 67 71
830 431 ▶ my @children = @{$block->{children}||[]};
Condition50%1/2
$block->{'children'} || []
l!l
670
MC/DC0%0/1
$block->{'children'} || []
$block->{'children'}
Truth table50%1/2
A
A= $block->{'children'}
Aresult
11
00
831 $block->{children} = [
832 139 bless({ content => 'raw' }, 'PPI::Token::Word'),
833 bless({
834 children => [
835 bless({
836 children => [
837 bless({ content => '$_O' }, 'PPI::Token::Symbol'),
838 ],
839 }, 'PPI::Statement::Expression'),
840 ],
841 start => bless({ content => '(' }, 'PPI::Token::Structure'),
842 finish => bless({ content => ')' }, 'PPI::Token::Structure'),
843 }, 'PPI::Structure::List'),
844 bless({ content => ';' }, 'PPI::Token::Structure'),
845 @children,
846 ],
847 }
848 139 return 1;
849 }
850  
851 38 ▶sub render {
Subroutine render: called CC=1 SCAR=0.0
Pod documented
852 117 my ($self, $template, @args) = @_;
853 129 my $compiled = $self->from_string($template);
854 119 return $compiled->render(@args);
855 }
856  
857 97 1;
858  
859 =head1 NAME
860  
861 Template::EmbeddedPerl - A template processing engine using embedding Perl code
862  
863 =head1 SYNOPSIS
864  
865 use Template::EmbeddedPerl;
866  
867 Create a new template object:
868  
869 my $template = Template::EmbeddedPerl->new(); # default open and close tags are '<%' and '%>'
870  
871 Compile a template from a string:
872  
873 my $compiled = $template->from_string('Hello, <%= shift %>!');
874  
875 execute the compiled template:
876  
877 my $output = $compiled->render('John');
878  
879 C<$output> is:
880  
881 Hello, John!
882  
883 You can also use class methods to create compiled templates
884 in one step if you don't need the reusable template object
885  
886 my $compiled = Template::EmbeddedPerl->from_string('Hello, <%= shift %>!');
887 my $output = $compiled->render('John');
888  
889 Or you can render templates from strings directly:
890  
891 my $template = Template::EmbeddedPerl->new(use_cache => 1); # cache compiled templates
892 my $output = $template->render('Hello, <%= shift %>!', 'John');
893  
894 Other class methods are available to create compiled templates from files, file handles,
895 and data sections. See the rest of the docs for more information.
896  
897 =head1 DESCRIPTION
898  
899 C<Template::EmbeddedPerl> is a template engine that allows you to embed Perl code
900 within template files or strings. It provides methods for creating templates
901 from various sources, including strings, file handles, and data sections.
902  
903 The module also supports features like helper functions, automatic escaping,
904 and customizable template compilation namespaces.
905  
906 Its quite similar to L<Mojo::Template> and other embedded Perl template engines
907 but its got one trick the others can't do (see L<EXCUSE> below).
908  
909 The core supports standalone composition with partials, layouts, named content
910 blocks, and optional typed view objects. Framework integrations can provide a
911 view resolver when logical child names need application-specific construction
912 or dependency injection.
913  
914 =head1 ACKNOWLEDGEMENTS
915  
916 I looked at L<Mojo::Template> and I lifted some code and docs from there. I also
917 copied some of their test cases. I was shooting for something reasonable similar
918 and potentially compatible with L<Mojo::Template> but with some additional features.
919 L<Template::EmbeddedPerl> is similiar to how template engines in popular frameworks
920 like Ruby on Rails and also similar to EJS in the JavaScript world. So nothing weird
921 here, just something people would understand and be comfortable with. A type of
922 lowest common denominator. If you know Perl, you will be able to use this after
923 a few minutes of reading the docs (or if you've used L<Mojo::Template> or L<Mason>
924 you might not even need that).
925  
926 =head1 EXCUSE
927  
928 Why create yet another one of these embedded Perl template engines? I wanted one
929 that could properly handle block capture like following:
930  
931 <% my @items = map { %>
932 <p><%= $_ %></p>
933 <% } @items %>
934  
935 Basically none of the existing ones I could find could handle this. If I'm wrong
936 and somehow there's a flag or approach in L<Mason> or one of the other ones that
937 can handle this please let me know.
938  
939 L<Mojo::Template> is close but you have to use C<begin> and C<end> tags to get a similar
940 effect and it's not as flexible as I'd like plus I want to be able to use signatures in
941 code like the following:
942  
943 <%= $f->form_for($person, sub($view, $fb, $person) { %>
944 <div>
945 <%= $fb->label('first_name') %>
946 <%= $fb->input('first_name') %>
947 <%= $fb->label('last_name') %>
948 <%= $fb->input('last_name') %>
949 </div>
950 <% }) %>
951  
952 Again, I couldn't find anything that could do this. Its actually tricky because of the way
953 you need to localize capture of template output when inside a block. I ended up using L<PPI>
954 to parse the template so I could properly find begin and end blocks and also distinguish between
955 control blocks (like C<if> an C<unless>) blocks that have a return like C<sub> or C<map> blocks.
956 In L<Mojo::Template> you can do the following (its the same but not as pretty to my eye):
957  
958 <% my $form = $f->form_for($person, begin %>
959 <% my ($view, $fb, $person) = @_; %>
960 <div>
961 <%= $fb->label('first_name') %>
962 <%= $fb->input('first_name') %>
963 <%= $fb->label('last_name') %>
964 <%= $fb->input('last_name') %>
965 </div>
966 <% end; %>
967  
968 On the other hand my system is pretty new and I'm sure there are bugs and issues I haven't
969 thought of yet. So you probably want to use one of the more mature systems like L<Mason> or
970 L<Mojo::Template> unless you really need the features I've added. Or your being forced to use
971 it because you're working for me ;)
972  
973 =head1 TEMPLATE SYNTAX
974  
975 The template syntax is similar to other embedded Perl template engines. You can embed Perl
976 code within the template using opening and closing tags. The default tags are C<< '<%' >> and
977 C<< '%>' >>, but you can customize them when creating a new template object. You should pick
978 open and closing tags that are not common in your template content.
979  
980 All templates get C<strict>, C<warnings> and C<utf8> enabled by default. Please note this
981 is different than L<Mojo::Template> which does not seem to have warnings enabled by default.
982 Since I like very strict templates this default makes sense to me but if you tend to play
983 fast and loose with your templates (for example you don't use C<my> to declare variables) you
984 might not like this. Feel free to complain to me, I might change it.
985  
986 Basic Patterns:
987  
988 <% Perl code %>
989 <%= Perl expression, replaced with result %>
990  
991 Examples:
992  
993 <% my @items = qw(foo bar baz) %>
994 <% foreach my $item (@items) { %>
995 <p><%= $item %></p>
996 <% } %>
997  
998 Would output:
999  
1000 <p>foo</p>
1001 <p>bar</p>
1002 <p>baz</p>
1003  
1004 You can also use the 'line' version of the tags to make it easier to embed Perl code, or at
1005 least potentially easier to read. For example:
1006  
1007 % my @items = qw(foo bar baz)
1008 % foreach my $item (@items) {
1009 <p><%= $item %></p>
1010 % }
1011  
1012 =head2 Smart Lines and Named Arguments
1013  
1014 Set C<smart_lines> to a true value to make a line beginning with C<< % >> or C<< %= >>
1015 a complete directive without a trailing delimiter. This is especially useful
1016 for declarative named template arguments:
1017  
1018 % args $name, $greeting = 'Hello', $heading = sub { "Hello, $name" }
1019 <p><%= $heading %></p>
1020  
1021 C<args> must be the first executable directive. An argument without a default
1022 is required; a scalar expression supplies a default; a coderef is a lazy
1023 default evaluated only when its argument is absent. An explicit C<undef> is a
1024 supplied value and does not evaluate a lazy default. Render arguments are named
1025 key/value pairs when a template declares C<args>.
1026  
1027  
1028 You can add '=' to the closing tag to indicate that the expression should be trimmed of leading
1029 and trailing whitespace. This is useful when you want to include the expression in a block of text.
1030 where you don't want the whitespace to affect the output.
1031  
1032 <%= Perl expression, replaced with result, trimmed =%>
1033  
1034 You can add '-' to the closing tag to trim whitespace after the tag through the next
1035 newline. This is useful when a readable code block should not emit a leading newline
1036 before the next element, for example in partial HTML responses.
1037  
1038 <% Perl code -%>
1039 <%= Perl expression, replaced with result -%>
1040  
1041 If you want to skip the newline after the closing tag you can use a backslash.
1042  
1043 <% Perl code %>\
1044 <%= Perl expression, replaced with result, no newline %>\
1045  
1046 You probably don't care about this so much with HTML since it collapses whitespace but it can be
1047 useful for other types of output like plain text or if you need some embedded Perl inside
1048 your JavaScript.
1049  
1050 If you really need that backslash in your output you can escape it with another backslash.
1051  
1052 <%= "This is a backslash: " %>\\
1053  
1054 If you really need to use the actual tags in your output you can escape them with a backslash.
1055  
1056 \<% => <%
1057 \<%= => <%=
1058 \%> => %>
1059 \%= => %=
1060 \% => %
1061  
1062 Lastly you can add full line comments to your templates that will be removed from the final
1063 output
1064  
1065 # This is a comment
1066 <p>Regular HTML</p>
1067  
1068 A comment is declared with a single C<#> at the start of the line (or with only whitespace preceeding it).
1069 This line will be removed from the output, including its newline. If you really need a '#'you can escape it
1070 with C<\#> (this is only needed if the '#' is at the beginning of the line, or there's only preceding whitespace.
1071  
1072 =head2 Interpolation Syntax
1073  
1074 If you want to embed Perl variables directly in the template without using the C<%= ... %> syntax,
1075 you can enable interpolation. This allows you to embed Perl variables directly in the template
1076 without using the C<%= ... %> syntax. For example:
1077  
1078 my $template = Template::EmbeddedPerl->new(interpolation => 1, prepend => 'my $name = shift');
1079 my $compiled = $template->from_string('Hello, $name!');
1080 my $output = $compiled->render('John');
1081  
1082 C<$output> is:
1083  
1084 Hello, John!
1085  
1086 This works by noticing a '$' followed by a Perl variable name (and method calls, etc). So if you
1087 need to put a real '$' in your code you will need to escape it with C<\$>.
1088  
1089 This only works on a single line and is intended to help reduce template complexity and noise
1090 for simple placeholder template sections. Nevertheless I did try top make it work with reasonable
1091 complex single variable expressions. Submit a test case if you find something that doesn't work
1092 which you think should.
1093  
1094 See the section on the interpolation configuration switch below for more information. This is
1095 disabled by default and I consider it experimental at this time since parsing Perl code with
1096 regular expressions is a bit of a hack.
1097  
1098 =head1 METHODS
1099  
1100 =head2 new
1101  
1102 my $template = Template::EmbeddedPerl->new(%args);
1103  
1104 Creates a new C<Template::EmbeddedPerl> object. Accepts the following arguments:
1105  
1106 =over 4
1107  
1108 =item * C<open_tag>
1109  
1110 The opening tag for template expressions. Default is C<< '<%' >>. You should use
1111 something that's not common in your template content.
1112  
1113 =item * C<close_tag>
1114  
1115 The closing tag for template expressions. Default is C<< '%>' >>.
1116  
1117 =item * C<expr_marker>
1118  
1119 The marker indicating a template expression. Default is C<< '=' >>.
1120  
1121 =item * C<sandbox_ns>
1122  
1123 The namespace where templates are compiled. Default is C<< 'Template::EmbeddedPerl::Sandbox' >>.
1124 This isolates unqualified symbols but is not a security boundary: templates execute arbitrary
1125 Perl and can access modules, files, processes, and application globals. Only compile templates
1126 from trusted sources.
1127  
1128 =item * C<directories>
1129  
1130 An array reference of directories to search for templates. Default is an empty array.
1131 A directory to search can be either a string or an array reference containing each part
1132 of the path to the directory. Directories will be searched in order listed.
1133  
1134 my $template = Template::EmbeddedPerl->new(directories=>['/path/to/templates']);
1135 my $template = Template::EmbeddedPerl->new(directories=>[['/path', 'to', 'templates']]);
1136  
1137 I don't do anything smart to make sure you don't reference templates in dangerous places.
1138 So be careful to make sure you don't let application users specify the template path.
1139  
1140 The first matching file wins. Partials, layouts, explicit typed-view templates,
1141 and convention-derived typed-view templates use this same ordered search path.
1142  
1143 =item * C<smart_lines>
1144  
1145 Boolean indicating whether a line beginning with C<< % >> or C<< %= >> is a complete
1146 directive. Default is C<0>. See L</Smart Lines and Named Arguments>.
1147  
1148 =item * C<view_namespace>
1149  
1150 Optional namespace prefix for logical typed-view class lookup and
1151 convention-based typed-view template lookup. For a logical name, the engine
1152 prefixes this namespace to find the class. For a view without an explicit
1153 template, the matching prefix is removed, C<::> becomes C</>, and each
1154 remaining CamelCase segment is converted to lowercase snake case. Acronym runs
1155 stay together: C<HTML>, C<HTMLPage>, and C<ContactList> become C<html>,
1156 C<html_page>, and C<contact_list>.
1157  
1158 For example, C<MyApp::View::HTML::ContactList> with
1159 C<view_namespace =E<gt> 'MyApp::View'> resolves C<html/contact_list> before the
1160 normal C<template_extension> is added.
1161  
1162 =item * C<view_factory>
1163  
1164 Optional coderef used to construct nested logical typed views. It receives
1165 C<< ($class, \%args, $context) >> and must return a blessed object. C<$class>
1166 is the class resolved from the logical name and C<view_namespace>; C<\%args>
1167 contains only values supplied by the template. Use it for dependency injection,
1168 such as C<root> and C<parent> relationships. Without a factory, the engine
1169 calls C<< $class->new(%args) >>.
1170  
1171 =item * C<template_extension>
1172  
1173 The file extension for template files. Default is C<< 'epl' >>. So for example:
1174  
1175 my $template = Template::EmbeddedPerl->new(directories=>['/path/to/templates', 'path/to/other/templates']);
1176 my $compiled = $template->from_file('hello');
1177  
1178 Would look for a file named C<hello.epl> in the directories specified.
1179  
1180 =item * C<auto_escape>
1181  
1182 Boolean indicating whether to automatically escape content. Default is C<< 0 >>.
1183 You probably want this enabled for web content to prevent XSS attacks. If you have this
1184 on and want to return actual HTML you can use the C<raw> helper function. Example:
1185
1186 <%= raw '<a href="http://example.com">Example</a>' %>
1187  
1188 Obviously you need to be careful with this.
1189  
1190 The C<raw> helper (also available as a method on the template object) takes the string
1191 and turns it into an instance of L<Template::EmbeddedPerl::SafeString>. The auto escape
1192 code when it sees that object knows to pass it thru without trying to escape it. The
1193 C<raw> helper has a version called C<safe> which does any needed encoding first (or passes
1194 unchanged any already created safe string objects).
1195  
1196 If the value is an object that does C<to_safe_string> then the object will first be converted
1197 to a safe string by calling it. Legacy C<render> methods pass the template
1198 engine as the first parameter; typed C<render_view> rendering passes the active
1199 view. That allows you to safely stringify objects without needing to do so
1200 manually.
1201  
1202 B<NOTE> we only check for objects with the C<to_safe_string> method when using C<auto_escape>
1203 If you are not using this safety feature and you are manually performing any needed escaping
1204 then you can just use ordinary overloading to stringify your object values.
1205  
1206 =item * C<auto_flatten_expr>
1207  
1208 Boolean indicating whether to automatically flatten expressions. Default is C<< 1 >>.
1209 What this means is that if you have an expression that returns an array we will join
1210 the array into a string before outputting it. Example:
1211  
1212 <% my @items = qw(foo bar baz); %>
1213 <%= map { "$_ " } @items %>
1214  
1215 Would output:
1216  
1217 foo bar baz
1218  
1219 =item * C<preamble>
1220  
1221 Add Perl code to the 'preamble' section of the compiled template. This is to top of the generated
1222 script prior to the anonymous sub representing your template.Default is an empty string. For example
1223 you can enable modern Perl features like signatures by setting this to C<< 'use v5.40;' >>.
1224  
1225 Use this to setup any pragmas or modules you need to use in your template code.
1226  
1227 =item * C<prepend>
1228  
1229 Perl code to prepend to the compiled template. Default is an empty string. This goes just inside the
1230 anonyous subroutine that is called to return your document string. For example you can use this to
1231 pull passed arguments off C<@_>.
1232  
1233 =item * C<helpers>
1234  
1235 A hash reference of helper functions available to the templates. Default is an empty hash.
1236 You can add your own helper functions to this hash and they will be available to the templates.
1237 Example:
1238  
1239 my $template = Template::EmbeddedPerl->new(helpers => {
1240 my_helper => sub { return 'Hello, World!' },
1241 });
1242  
1243 =item * C<use_cache>
1244  
1245 Boolean indicating whether to cache compiled templates. Default is C<< 0 >>.
1246 If you set this to C<< 1 >>, the module will cache compiled templates in memory. This is
1247 only useful if you are throwing away the template object after compiling a template.
1248 For example:
1249  
1250 my $ep = Template::EmbeddedPerl->new(use_cache => 1);
1251 my $output = $ep->render('Hello, <%= shift %>!', 'John');
1252  
1253 In the case above since you are not capturing the compiled template object each time
1254 you call C<render> you are recompiling the template. which could get expensive.
1255  
1256 On the other hand if you are keeping the template object around and reusing it you don't
1257 need to enable this. Example:
1258  
1259 my $ep = Template::EmbeddedPerl->new(use_cache => 1);
1260 my $compiled = $ep->from_string('Hello, <%= shift %>!');
1261 my $output = $compiled->render('John');
1262  
1263 In the valid above the compiled template is cached and reused each time you call C<render>.
1264  
1265 Obviously this only works usefully in a persistent environment like mod_perl or a PSGI server.
1266  
1267 =item * C<comment_mark>
1268  
1269 Defaults to '#'. Indicates the beginning of a comment in the template which is to be removed
1270 from the output.
1271  
1272 =item * C<interpolation>
1273  
1274 Boolean indicating whether to enable interpolation in the template. Default is C<< 0 >> (disabled).
1275  
1276 Interpolation allows you to embed Perl variables directly in the template without using the
1277 C<%= ... %> syntax. For example:
1278  
1279 my $template = Template::EmbeddedPerl->new(interpolation => 1, prepend => 'my ($name) = @_');
1280 my $output = $template->render('Hello, $name!', 'John');
1281  
1282 This will output:
1283  
1284 Hello, John!
1285  
1286 Interpolation is reasonable sophisticated and will handle many cases including have more
1287 then one variable in a line. For example:
1288  
1289 my $template = Template::EmbeddedPerl->new(interpolation => 1, prepend => 'my ($first, $last) = @_');
1290 my $output = $template->render('Hello, $first $last!', 'John', 'Doe');
1291  
1292 This will output:
1293  
1294 Hello, John Doe!
1295  
1296 It can also handle variables that are objects and call methods on them. For example:
1297  
1298 my $template = Template::EmbeddedPerl->new(interpolation => 1, prepend => 'my ($person_obj) = @_');
1299 my $output = $template->render('Hello, $person_obj->first_name $person_obj->last_name!', Person->new('John', 'Doe'));
1300  
1301 This will output:
1302  
1303 Hello, John Doe!
1304  
1305 If you need to disambiguate a variable from following text you enclose the variable in curly braces.
1306  
1307 my $template = Template::EmbeddedPerl->new(interpolation => 1);
1308 my $output = $template->render('Hello, ${arg}XXX', 'John');
1309  
1310 This will output:
1311  
1312 Hello, JohnXXX
1313  
1314 You can nest method calls and the methods can contain arguments of varying complexity, including
1315 anonymous subroutines. There is a limited ability to span lines; you make break lines across the
1316 deference operator and in many cases across balanced parenthesis, square and curly brackets. If you
1317 do so you cannot mix 'template text' with the Perl code. For example:
1318  
1319 <div class="name">
1320 $person->profile
1321 ->first_name
1322 </div>
1323  
1324 and
1325  
1326 $obj->compute(
1327 sub {
1328 my $arg = shift;
1329 return $arg * 2;
1330 }
1331 )
1332  
1333 are both valid. But this will fail:
1334  
1335 <p>
1336 $arg->compute(sub {
1337 my $value = shift;
1338 $value = $value * 5
1339 <div>$value</div>
1340 })
1341 </p>
1342  
1343 For this case you need to use the C<%= ... %> syntax or %= and %:
1344  
1345 <p>
1346 %= $arg->compute(sub {
1347 % my $value = shift;
1348 % $value = $value * 5
1349 <div>$value</div>
1350 % })
1351 </p>
1352  
1353 You can review the existing test case at C<t/interpolation.t> for examples.
1354  
1355 This works by noticing a '$' followed by a Perl variable name (and method calls, etc). So if you
1356 need to put a real '$' in your code you will need to escape it with C<\$>. It does not work
1357 for other perl sigils at this time (for example '@' or '%').
1358  
1359 This feature is experimental so if you have trouble with it submit a trouble ticket with test
1360 case (review the C<t/interpolation.t> test cases for examples of the type of test cases I need).
1361 I intend interpolation to be a 'sweet spot' feature that tries to reduce amount of typing
1362 and overall template 'noise', not something that fully parses Perl code. Anything super crazy
1363 should probably be encapsulated in a helper function anyway.
1364  
1365 =back
1366  
1367 =head2 from_string
1368  
1369 my $compiled = $template->from_string($template_string, %args);
1370  
1371 Creates a compiled template from a string. Accepts the template content as a
1372 string and optional arguments to modify behavior. Returns a
1373 C<Template::EmbeddedPerl::Compiled> object.
1374  
1375 pass 'source => $path' to the arguments to specify the source of the template if you
1376 want neater error messages.
1377  
1378 This can be called as a class method as well::
1379  
1380 my $compiled = Template::EmbeddedPerl->from_string($template_string, %args);
1381  
1382 Useful if you don't need to keep the template object around. This works
1383 for all the other methods as well (C<from_file>, C<from_fh>, C<from_data>).
1384  
1385 =head2 from_file
1386  
1387 my $compiled = $template->from_file($file_name, %args);
1388  
1389 Creates a compiled template from a file. Accepts the filename (without extension)
1390 and optional arguments. Searches for the file in the directories specified during
1391 object creation.
1392  
1393 =head2 from_fh
1394  
1395 my $compiled = $template->from_fh($filehandle, %args);
1396  
1397 Creates a compiled template from a file handle. Reads the content from the
1398 provided file handle and processes it as a template.
1399  
1400 pass 'source => $path' to the arguments to specify the source of the template if you
1401 want neater error messages.
1402  
1403 =head2 from_data
1404  
1405 my $compiled = $template->from_data($package, %args);
1406  
1407 Creates a compiled template from the __DATA__ section of a specified package.
1408 Returns a compiled template object or dies if the package cannot be loaded or
1409 no __DATA__ section is found.
1410  
1411 =head2 trim
1412  
1413 my $trimmed = $template->trim($string);
1414  
1415 Trims leading and trailing whitespace from the provided string. Returns the
1416 trimmed string.
1417  
1418 =head2 mtrim
1419  
1420 Same as C<trim> but trims leading and trailing whitespace for a multiline string.
1421  
1422 =head2 default_helpers
1423  
1424 my %helpers = $template->default_helpers;
1425  
1426 Returns a hash of default helper functions available to the templates.
1427  
1428 =head2 get_helpers
1429  
1430 my %helpers = $template->get_helpers($helper_name);
1431  
1432 Returns a specific helper function or all helper functions if no name is provided.
1433  
1434 =head2 parse_template
1435  
1436 my @parsed = $template->parse_template($template);
1437  
1438 Parses the provided template content and returns an array of parsed blocks.
1439  
1440 =head2 compile
1441  
1442 my $code = $template->compile($template, @parsed);
1443  
1444 Compiles the provided template content into executable Perl code. Returns a
1445 code reference.
1446  
1447 =head2 directory_for_package
1448  
1449 my $directory = $template->directory_for_package($package);
1450  
1451 Returns the directory containing the package file.
1452 If you don't provide a package name it will use the current package for C<$template>.
1453  
1454 Useful if you want to load templates from the same directory as your package.
1455  
1456 =head2 render
1457  
1458 my $output = $template->render($template, @args);
1459  
1460 Compiles and executes the provided template content with the given arguments. You might
1461 want to enable the cache if you are doing this.
1462  
1463 Compatibility note: C<render> and C<Template::EmbeddedPerl::Compiled::render>
1464 keep every legacy argument, including a blessed first argument, in C<@_>. They
1465 do not infer a typed C<$self>.
1466  
1467 =head2 render_view
1468  
1469 B<Experimental:> Typed view support, including C<render_view>, C<view>,
1470 C<view_namespace>, and C<view_factory>, may change as real-world integration
1471 needs become clearer.
1472  
1473 my $output = $template->render_view($view);
1474  
1475 Renders a preconstructed blessed view object. Its template receives that object
1476 as lexical C<$self>. A non-blessed value is an error. Root and nested views use
1477 the same template precedence:
1478  
1479 =over 4
1480  
1481 =item 1.
1482  
1483 A nonempty C<< $view->template >> result.
1484  
1485 =item 2.
1486  
1487 The C<view_namespace> convention.
1488  
1489 =back
1490  
1491 Use the C<view> helper for a nested typed object. C<< view $object >> renders a
1492 preconstructed child, which bypasses construction. C<< view $logical_name,
1493 %args >> resolves its class from C<view_namespace> and calls
1494 C<< $class->new(%args) >> by default. If configured, C<view_factory> alone
1495 performs construction and receives C<< ($class, \%args, $context) >>; use it
1496 to inject dependencies. The final coderef, if any, is a wrapper body. In that
1497 callback lexical C<$self> remains the caller; the callback argument is the
1498 wrapper object, and the wrapper template itself receives the wrapper as
1499 C<$self>.
1500  
1501 The core accepts any blessed object. Moo is used only by the test and cookbook
1502 examples. L<Template::EmbeddedPerl::Cookbook::TypedViews> contains complete Moo
1503 examples for applications that use it.
1504  
1505 =head1 HELPER FUNCTIONS
1506  
1507 The module provides a set of default helper functions that can be used in templates.
1508  
1509 =over 4
1510  
1511 =item * C<raw>
1512  
1513 Returns a string as a safe string object without escaping. Useful if you
1514 want to return actual HTML to your template but you better be
1515 sure that HTML is safe.
1516  
1517 <%= raw '<a href="http://example.com">Example</a>' %>
1518  
1519 =item * C<safe>
1520  
1521 Returns a string as a safe html escaped string object that will not be
1522 escaped again.
1523  
1524 =item * C<safe_concat>
1525  
1526 Like C<safe> but for multiple strings. This will concatenate the strings into
1527 a single string object that will not be escaped again.
1528  
1529 =item * C<html_escape>
1530  
1531 Escapes HTML entities in a string. This differs for C<safe> in that it will
1532 just do the escaping and not wrap the string in a safe string object.
1533  
1534 =item * C<url_encode>
1535  
1536 Encodes a string for use in a URL.
1537  
1538 =item * C<escape_javascript>
1539  
1540 Escapes a value for use inside a JavaScript string, including preventing a closing
1541 C<script> tag from terminating an enclosing HTML script element. This is not a general
1542 JavaScript sanitizer; use a context-appropriate sanitizer for untrusted code.
1543  
1544 =item * C<trim>
1545  
1546 Trims leading and trailing whitespace from a string.
1547  
1548 =item * C<partial>
1549  
1550 C<< partial $identifier, %args >> renders an untyped template immediately with
1551 the caller's C<$self>. Its output is safe rendered output and is not escaped a
1552 second time by C<auto_escape>.
1553  
1554 =item * C<layout>
1555  
1556 C<< layout $identifier, %args >> registers an untyped outer template for the
1557 current output. Layout arguments are independent named arguments for the
1558 layout. Multiple layouts nest with the first declaration outermost.
1559  
1560 =item * C<yield>
1561  
1562 C<yield> returns the current body. C<< yield $name >> returns named content
1563 captured in the current render frame.
1564  
1565 =item * C<content_for>, C<content_replace>, and C<has_content>
1566  
1567 C<< content_for $name, sub { ... } >> appends named content in render order.
1568 C<content_replace> replaces it, and C<< has_content $name >> reports whether
1569 the named content is nonempty.
1570  
1571 =item * C<view>
1572  
1573 Renders a typed child as described in L</render_view>. The optional final
1574 coderef supplies the wrapper body.
1575  
1576 =back
1577  
1578 =head1 ERROR HANDLING
1579  
1580 If an error occurs during template compilation or rendering, the module will
1581 throw an exception with a detailed error message. The error message includes
1582 the source of the template, the line number, and the surrounding lines of the
1583 template to help with debugging. Example:
1584  
1585 Can't locate object method "input" at /path/to/templates/hello.yat line 4.
1586  
1587 3: <%= label('first_name') %>
1588 4: <%= input('first_name') %>
1589 5: <%= errors('last_name') %>
1590  
1591 Each top-level C<render>, compiled-template C<render>, and C<render_view> call
1592 creates exactly one render frame. Nested partials, layouts, and views share that
1593 frame. Render cycles are rejected with their active chain. A nested exception is
1594 decorated with one source-aware C<Render stack>; failed rendering restores the
1595 frame's body, named content, layouts, and stack state so the engine can be
1596 reused for a later top-level render.
1597  
1598 =head1 ENVIRONMENT VARIABLES
1599  
1600 The module respects the following environment variables:
1601  
1602 =over 4
1603  
1604 =item * C<DEBUG_TEMPLATE_EMBEDDED_PERL>
1605  
1606 Set this to a true value to print the compiled template code to the console. Useful
1607 when trying to debug difficult compilation issues, especially given this is early
1608 access code and you might run into bugs.
1609  
1610 =back
1611  
1612 =head1 REPORTING BUGS & GETTING HELP
1613  
1614 If you find a bug, please report it on the GitHub issue tracker at
1615 L<https://github.com/jjn1056/Template-EmbeddedPerl/issues>. The bug tracker is
1616 the easiest way to get help with this module from me but I'm also on irc.perl.org
1617 under C<jnap>.
1618  
1619 =head1 DEDICATION
1620  
1621 This module is dedicated to the memory of my dog Bear who passed away on 17 August 2024.
1622 He was a good companion and I miss him.
1623  
1624 If this module is useful to you please consider donating to your local animal shelter
1625 or rescue organization.
1626  
1627 =head1 AUTHOR
1628  
1629 John Napiorkowski, C<< <jjnapiork@cpan.org> >>
1630  
1631 =head1 LICENSE AND COPYRIGHT
1632  
1633 This library is free software; you can redistribute it and/or modify it under the
1634 same terms as Perl itself.
1635  
1636 =cut
1637  
1638  
1639 __END__
« lib/Template/EmbeddedPerl/SafeString.pm ↑ Summary lib/Template/EmbeddedPerl/Utils.pm »