Pure.pm

filter: Statementstmt 92.8% 219 / 236 Branchbran 83.6% 97 / 116 Conditioncond 77.7% 28 / 36 MC/DCmcdc 57.8% 11 / 19 Subroutinesub 97.8% 45 / 46 Podpod 50.0% 7 / 14 totaltotal 87.1% 407 / 467 CC 76 SCAR 20.0
CC
76
Cov
89%
_process_mode
18.6
_process_sub_data
15.1
_process_dom_recursive
12.0
CRAP 7.4
« Pure/DataContext.pm ↑ Summary Pure/DataProxy.pm »
1 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package Template::Pure;
5  
6 13 our $VERSION = '0.007';
7  
8 13 ▶use DOM::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use Template::Pure::ParseUtils;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 13 ▶use Template::Pure::Filters;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 13 ▶use Template::Pure::DataContext;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 13 ▶use Template::Pure::DataProxy;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 13 ▶use Template::Pure::EncodedString;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 13 ▶use Template::Pure::Iterator;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 sub new {
18 17 ▶ my ($proto, %args) = @_;
Subroutine new: called CC=3 SCAR=12.5
Pod documented
19 17 ▶ my $class = ref($proto) || $proto;
Condition33%1/3
ref $proto || $proto
l!l&&r!l&&!r
0170
MC/DC0%0/2
ref $proto || $proto
ref $proto $proto
Truth table33%1/3
A || B
A= ref $protoB= $proto
ABresult
1X1
011
000
20 return bless +{
21 filters => $args{filters} || +{},
22 dom => DOM::Tiny->new($args{template}),
23 directives => $args{directives},
24 17 ▶ }, $class;
Condition50%1/2
$args{'filters'} || {}
l!l
017
MC/DC0%0/1
$args{'filters'} || {}
$args{'filters'}
Truth table50%1/2
A
A= $args{'filters'}
Aresult
11
00
25 }
26  
27 sub render {
28 17 ▶ my ($self, $data_proto, $extra_directives) = @_;
Subroutine render: called CC=1 SCAR=0.0
Pod documented
29 17 return $self->process_dom($data_proto, $extra_directives)->to_string;
30 }
31  
32 sub process_dom {
33 17 ▶ my ($self, $data_proto, $extra_directives) = @_;
Subroutine process_dom: called CC=2 SCAR=7.0
Pod documented
34 return $self->_process_dom_recursive(
35 $data_proto,
36 $self->{dom},
37 17 @{$self->{directives}},
38 17 ▶ @{$extra_directives||[]},
Branch: 1 branch
BranchTrueFalseTotal
$extra_directives or [] 17 0 17
39 );
40 }
41  
42 10 ▶sub default_filters { Template::Pure::Filters->all }
Subroutine default_filters: called CC=1 SCAR=0.0
Pod undocumented
43 80 ▶sub parse_match_spec { Template::Pure::ParseUtils::parse_match_spec($_[1]) }
Subroutine parse_match_spec: called CC=1 SCAR=0.0
Pod undocumented
44 47 ▶sub parse_data_spec { Template::Pure::ParseUtils::parse_data_spec($_[1]) }
Subroutine parse_data_spec: called CC=1 SCAR=0.0
Pod undocumented
45 7 ▶sub parse_data_template { Template::Pure::ParseUtils::parse_data_template($_[1]) }
Subroutine parse_data_template: called CC=1 SCAR=0.0
Pod undocumented
46 5 ▶sub parse_itr_spec { Template::Pure::ParseUtils::parse_itr_spec($_[1]) }
Subroutine parse_itr_spec: called CC=1 SCAR=0.0
Pod undocumented
47 69 ▶sub escape_html { Template::Pure::Filters::escape_html($_[1]) }
Subroutine escape_html: called CC=1 SCAR=0.0
Pod documented
48 18 ▶sub encoded_string { Template::Pure::EncodedString->new($_[1]) }
Subroutine encoded_string: called CC=1 SCAR=0.0
Pod documented
49  
50 sub data_at_path {
51 0 ▶ my ($self, $data, $path) = @_;
Subroutine data_at_path: not called CC=1 SCAR=6.9
Pod documented
52 0 my %data_spec = $self->parse_data_spec($path);
53 0 return $self->_value_from_data($data, %data_spec);
54 }
55  
56 sub at_or_die {
57 10 ▶ my ($self, $dom, $css) = @_;
Subroutine at_or_die: called CC=3 SCAR=11.0
Pod undocumented
58 10 ▶ my $new = $css eq '.' ? $dom : $dom->at($css);
Branch: 1 branch
BranchTrueFalseTotal
$css eq '.' ? : 1 9 10
59 10 ▶ die "$css is not a matching path" unless defined $new;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $new 0 10 10
60 10 return $new;
61 }
62  
63 sub _process_dom_recursive {
64 37 ▶ my ($self, $data_proto, $dom, @directives) = @_;
Subroutine _process_dom_recursive: called CC=12 SCAR=24.9
65  
66 37 ▶ $self->{root_data} = $data_proto unless exists $self->{root_data};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"root_data"} 17 20 37
67  
68 37 my $data = Template::Pure::DataContext->new($data_proto, $self->{root_data});
69  
70 37 ($data, @directives) = $self->_process_directive_instructions($dom, $data, @directives);
71  
72 37 ▶ while(@directives) {
Branch: 1 branch
BranchTrueFalseTotal
if (@directives) 74 37 111
73 74 my %match_spec = $self->parse_match_spec (shift @directives);
74 74 my $action_proto = shift @directives;
75  
76 74 ▶ $dom = $dom->root if $match_spec{absolute};
Branch: 1 branch
BranchTrueFalseTotal
if $match_spec{"absolute"} 0 74 74
77  
78 74 ▶ if($match_spec{mode} eq 'filter') {
Branch: 5 branches
BranchTrueFalseTotal
if ($match_spec{'mode'} eq 'filter') { } 1 73 74
elsif ((ref $action_proto || '') eq 'HASH') { } 8 65 73
elsif ((ref $action_proto || '') eq 'ARRAY') { } 5 60 65
elsif ((ref $action_proto || '') eq 'CODE') { } 3 57 60
elsif (builtin::blessed($action_proto)) { } 4 53 57
79 1 $self->_process_dom_filter($dom, $data, $match_spec{css}, $action_proto);
80 ▶ } elsif((ref($action_proto)||'') eq 'HASH') {
Condition100%2/2
ref $action_proto || ''
l!l
2350
MC/DC100%1/1
ref $action_proto || ''
ref $action_proto
Truth table100%2/2
A
A= ref $action_proto
Aresult
11
00
81 8 $self->_process_sub_data($dom, $data, \%match_spec, %{$action_proto});
82 ▶ } elsif((ref($action_proto)||'') eq 'ARRAY') {
Condition100%2/2
ref $action_proto || ''
l!l
1550
MC/DC100%1/1
ref $action_proto || ''
ref $action_proto
Truth table100%2/2
A
A= ref $action_proto
Aresult
11
00
83 5 $self->process_sub_directives($dom, $data->value, $match_spec{css}, @{$action_proto});
84 ▶ } elsif((ref($action_proto)||'') eq 'CODE') {
Condition100%2/2
ref $action_proto || ''
l!l
1050
MC/DC100%1/1
ref $action_proto || ''
ref $action_proto
Truth table100%2/2
A
A= ref $action_proto
Aresult
11
00
85 3 $self->_process_code($dom, $data, $action_proto, %match_spec);
86 } elsif(Scalar::Util::blessed($action_proto)) {
87 4 $self->_process_obj($dom, $data, $action_proto, %match_spec);
88 } else {
89 53 my $value = $self->_value_from_action_proto($dom, $data, $action_proto, %match_spec);
90 53 $self->_process_match_spec($dom, $value, %match_spec);
91 }
92 }
93  
94 37 return $dom;
95 }
96  
97 sub _process_obj {
98 4 ▶ my ($self, $dom, $data, $obj, %match_spec) = @_;
Subroutine _process_obj: called CC=4 SCAR=14.6
99 4 ▶ if($obj->isa(ref $self)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($obj->isa(ref $self)) { } 3 1 4
elsif ($obj->can('TO_HTML')) { } 1 0 1
100 3 my $value = $self->_value_from_template_obj($dom, $data, $obj, %match_spec);
101 3 $self->_process_match_spec($dom, $value, %match_spec);
102 } elsif($obj->can('TO_HTML')) {
103 1 my $css = $match_spec{css};
104 1 ▶ if($css eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($css eq '.') { } 0 1 1
105 0 my $value = $obj->TO_HTML($self, $dom, $data->value);
106 0 $self->_process_mode($dom, $value, %match_spec);
107 } else {
108 1 my $collection = $dom->find($css);
109 $collection->each(sub {
110 2 ▶ my $value = $obj->TO_HTML($self, $_, $data->value);
Subroutine __ANON__: called CC=1 SCAR=0.0
111 2 $self->_process_mode($_, $value, %match_spec);
112 1 });
113 }
114 } else {
115 0 die "Can't process object of type $obj.";
116 }
117  
118 }
119  
120 sub _value_from_action_proto {
121 57 ▶ my ($self, $dom, $data, $action_proto, %match_spec) = @_;
Subroutine _value_from_action_proto: called CC=4 SCAR=14.6
122 57 ▶ if(ref \$action_proto eq 'SCALAR') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref \$action_proto eq 'SCALAR') { } 51 6 57
elsif ((ref $action_proto || '') eq 'SCALAR') { } 6 0 6
123 51 return $self->_value_from_scalar_action($data, $action_proto);
124 ▶ } elsif((ref($action_proto)||'') eq 'SCALAR') {
Condition50%1/2
ref $action_proto || ''
l!l
60
MC/DC0%0/1
ref $action_proto || ''
ref $action_proto
Truth table50%1/2
A
A= ref $action_proto
Aresult
11
00
125 6 return $self->_value_from_dom($dom, $$action_proto);
126 } else {
127 0 die "I encountered an action I don't know what to do with: $action_proto";
128 }
129 }
130  
131 sub _value_from_scalar_action {
132 51 ▶ my ($self, $data, $action_proto) = @_;
Subroutine _value_from_scalar_action: called CC=6 SCAR=17.9
133  
134 ## If a $action_proto contains a ={ with no | first OR it contains a ={ and no |
135 ## That means it is a string with placeholders
136  
137 51 my $first_pipe = index($action_proto, '|');
138 51 my $first_open = index($action_proto, '={');
139
140 51 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if ($first_open >= 0 and $first_open < $first_pipe or $first_open >= 0 and $first_pipe == -1) { } 7 44 51
Condition100%9/9
$first_open >= 0 and $first_open < $first_pipe or $first_open >= 0 and $first_pipe == -1
l!l&&r!l&&!r
3444
$first_open >= 0 and $first_open < $first_pipe
!ll&&!rl&&r
4353
$first_open >= 0 and $first_pipe == -1
!ll&&!rl&&r
4314
MC/DC100%4/4
$first_open >= 0 and $first_open < $first_pipe or $first_open >= 0 and $first_pipe == -1
$first_open >= 0 $first_open < $first_pipe $first_open >= 0 $first_pipe == -1
Truth table57%4/7
A and B or C and D
A= $first_open >= 0B= $first_open < $first_pipeC= $first_open >= 0D= $first_pipe == -1
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
141 (
142 ($first_open >= 0) &&
143 ($first_open < $first_pipe)
144 ) || (
145 ($first_open >= 0) &&
146 ($first_pipe == -1)
147 )
148 ) {
149 my @parts = map {
150 7 ▶ ref $_ ? $self->_value_from_data($data, %$_) : $_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 15 8 23
151 } $self->parse_data_template($action_proto);
152 7 return join('', @parts);
153 } else {
154 44 my %data_spec = $self->parse_data_spec($action_proto);
155 44 return $self->_value_from_data($data, %data_spec);
156 }
157 }
158  
159 sub _process_code {
160 3 ▶ my ($self, $dom, $data, $code, %match_spec) = @_;
Subroutine _process_code: called CC=2 SCAR=6.9
161 3 my $css = $match_spec{css};
162 3 ▶ if($css eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($css eq '.') { } 1 2 3
163 1 my $value = $code->($self, $dom, $data->value);
164 1 $self->_process_mode($dom, $value, %match_spec);
165 } else {
166 2 my $collection = $dom->find($css);
167 $collection->each(sub {
168 6 ▶ my $value = $code->($self, $_, $data->value);
Subroutine __ANON__: called CC=1 SCAR=0.0
169 6 $self->_process_mode($_, $value, %match_spec);
170 2 });
171 }
172 }
173  
174 sub _value_from_template_obj {
175 4 ▶ my ($self, $dom, $data, $template, %match_spec) = @_;
Subroutine _value_from_template_obj: called CC=1 SCAR=0.0
176 4 my $content = $self->_value_from_dom($dom, \%match_spec);
177 4 my $new_data = Template::Pure::DataProxy->new(
178 $data->value,
179 content => $self->encoded_string($content));
180
181 4 return $self->encoded_string($template->render($new_data));
182 }
183  
184 sub _process_directive_instructions {
185 37 ▶ my ($self, $dom, $data, @directives) = @_;
Subroutine _process_directive_instructions: called CC=4 SCAR=13.9
186 37 ▶ if( (ref($directives[0])||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $directives[0] || "") eq "HASH") 2 35 37
Condition100%2/2
ref $directives[0] || ''
l!l
235
MC/DC100%1/1
ref $directives[0] || ''
ref $directives[0]
Truth table100%2/2
A
A= ref $directives[0]
Aresult
11
00
187 2 my %map = %{shift(@directives)};
188 2 my %new_data;
189 2 foreach my $key (keys %map) {
190 4 $new_data{$key} = $self->_value_from_action_proto($dom, $data, $map{$key});
191 }
192 2 $data = Template::Pure::DataContext->new(\%new_data);
193 }
194 37 return ($data, @directives);
195 }
196  
197 sub _process_sub_data {
198 8 ▶ my ($self, $dom, $data, $match_spec, %action) = @_;
Subroutine _process_sub_data: called CC=14 SCAR=27.1
199  
200 # I don't know what it means to match repeat on attribes or append/prepent
201 # right now, so just doing match on the CSS and welcome specifications for
202 # this behavior.
203  
204 8 my $css = $match_spec->{css};
205
206 # Pull out any sort or filters
207 8 ▶ my $sort_cb = exists $action{order_by} ? delete $action{order_by} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $action{'order_by'} ? : 2 6 8
208 8 ▶ my $filter_cb = exists $action{filter} ? delete $action{filter} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $action{'filter'} ? : 1 7 8
209 8 ▶ my $display_fields = exists $action{display_fields} ? delete $action{display_fields} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $action{'display_fields'} ? : 0 8 8
210 8 ▶ my $following_directives = exists $action{directives} ? delete $action{directives} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $action{'directives'} ? : 1 7 8
211  
212 8 my ($sub_data_proto, $sub_data_action) = %action;
213  
214 8 ▶ if(index($sub_data_proto,'<-') > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($sub_data_proto, '<-') > 0) { } 5 3 8
215  
216 5 ▶ die "Action for '$sub_data_proto' must be an arrayref of new directives"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $sub_data_action eq "ARRAY" 0 5 5
217 unless ref $sub_data_action eq 'ARRAY';
218  
219  
220 5 my ($new_key, $itr_data_spec) = $self->parse_itr_spec($sub_data_proto);
221 5 my $itr_data_proto = $self->_value_from_data($data, %$itr_data_spec);
222  
223 ## For now if the found value is undef, we second it along ti be trimmed
224 ## this behavior might be tweaked as examples of usage arise, also for now
225 ## we just pass through an empty iterator instead of considering it undef
226 ## ie [] is not considered like undef for now...
227  
228 5 ▶ return $self->_process_match_spec($dom, $itr_data_proto, %$match_spec)
Branch: 1 branch
BranchTrueFalseTotal
if $self->_value_is_undef($itr_data_proto) 1 4 5
229 if $self->_value_is_undef($itr_data_proto);
230  
231 4 my %options;
232 4 ▶ if($display_fields) {
Branch: 1 branch
BranchTrueFalseTotal
if ($display_fields) 0 4 4
233 0 $options{display_fields} = $display_fields;
234 }
235  
236 4 my $iterator = Template::Pure::Iterator->from_proto($itr_data_proto, $sort_cb, $filter_cb, \%options);
237
238 4 ▶ if($css eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($css eq '.') { } 0 4 4
239 0 $self->_process_iterator($dom, $new_key, $iterator, @{$sub_data_action});
240 } else {
241 4 my $collection = $dom->find($css);
242 $collection->each(sub {
243 4 ▶ $self->_process_iterator($_, $new_key, $iterator, @{$sub_data_action});
Subroutine __ANON__: called CC=1 SCAR=0.0
244 4 });
245 }
246 } else {
247 3 my %sub_data_spec = $self->parse_data_spec($sub_data_proto);
248 3 my $value = $self->_value_from_data($data, %sub_data_spec);
249  
250 ## If the value is undefined, we dont' continue... should we remove all this...?
251 3 ▶ if(ref $sub_data_action eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $sub_data_action eq 'ARRAY') { } 2 1 3
elsif (builtin::blessed($sub_data_action) and $sub_data_action->isa(ref $self)) { } 1 0 1
252 2 $self->process_sub_directives($dom, $value, $css, @{$sub_data_action});
253 ▶ } elsif(Scalar::Util::blessed($sub_data_action) && $sub_data_action->isa(ref $self)) {
Condition33%1/3
builtin::blessed($sub_data_action) and $sub_data_action->isa(ref $self)
!ll&&!rl&&r
001
MC/DC0%0/2
builtin::blessed($sub_data_action) and $sub_data_action->isa(ref $self)
builtin::blessed($sub_data_action) $sub_data_action->isa(ref $self)
Truth table33%1/3
A and B
A= builtin::blessed($sub_data_action)B= $sub_data_action->isa(ref $self)
ABresult
0X0
100
111
254 1 my $new_data = Template::Pure::DataContext->new($value);
255 1 my $new_value = $self->_value_from_template_obj($dom, $new_data, $sub_data_action, %$match_spec);
256 1 $self->_process_match_spec($dom, $new_value, %$match_spec);
257 } else {
258 0 die "Don't know how to process $value on $css for $sub_data_action";
259 }
260 }
261  
262 ## Todo... not sure if this is right or useful
263 7 ▶ if($following_directives) {
Branch: 1 branch
BranchTrueFalseTotal
if ($following_directives) 1 6 7
264 1 $self->process_sub_directives($dom, $data, $css, @{$following_directives});
265 }
266 }
267  
268 sub _process_iterator {
269 4 ▶ my ($self, $dom, $key, $iterator, @actions) = @_;
Subroutine _process_iterator: called CC=2 SCAR=6.9
270 4 my $new_dom = DOM::Tiny->new($dom);
271 4 ▶ while(my $datum = $iterator->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $datum = $iterator->next) 11 4 15
272 11 my $new_data = +{
273 $key => $datum,
274 i => $iterator,
275 };
276 11 $self->_process_dom_recursive($new_data, $new_dom->descendant_nodes->[0], @actions);
277 11 $dom->replace($new_dom); #Not sure why this is actually working....
278 #$iterator->is_first ? $dom->replace($new_dom) : $dom->append($new_dom);
279 }
280 }
281  
282 sub process_sub_directives {
283 8 ▶ my ($self, $dom, $data, $css, @directives) = @_;
Subroutine process_sub_directives: called CC=2 SCAR=7.2
Pod undocumented
284 8 ▶ if($css eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($css eq '.') { } 0 8 8
285 0 $self->_process_dom_recursive($data, $dom, @directives);
286 } else {
287 8 my $collection = $dom->find($css);
288 $collection->each(sub {
289 9 ▶ $self->_process_dom_recursive($data, $_, @directives);
Subroutine __ANON__: called CC=1 SCAR=0.0
290 8 });
291 }
292 }
293  
294 sub _value_from_dom {
295 10 ▶ my $self = shift;
Subroutine _value_from_dom: called CC=6 SCAR=17.9
296 10 my $dom = shift;
297 10 ▶ my %match_spec = ref $_[0] ? %{$_[0]} : $self->parse_match_spec($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 4 6 10
298  
299 10 ▶ $dom = $dom->root if $match_spec{absolute};
Branch: 1 branch
BranchTrueFalseTotal
if $match_spec{"absolute"} 3 7 10
300  
301 ## TODO, perhaps this could do a find instead of at and return
302 ## a collection, which populates an iterator if requested?
303  
304 10 ▶ if($match_spec{target} eq 'content') {
Branch: 3 branches
BranchTrueFalseTotal
if ($match_spec{'target'} eq 'content') { } 4 6 10
elsif ($match_spec{'target'} eq 'node') { } 5 1 6
elsif (my $attr = ${$match_spec{'target'};}) { } 1 0 1
305 4 return $self->encoded_string($self->at_or_die($dom, $match_spec{css})->content);
306 } elsif($match_spec{target} eq 'node') {
307 ## When we want a full node, with HTML tags, we encode the string
308 ## since I presume they want a copy not escaped. T 'think' this is
309 ## the commonly desired thing and you can always apply and escape_html filter
310 ## yourself when you don't want it.
311 5 return $self->encoded_string($self->at_or_die($dom, $match_spec{css})->to_string);
312 1 } elsif(my $attr = ${$match_spec{target}}) {
313 ## TODO not sure what if any encoding we need here.
314 1 return $self->at_or_die($dom, $match_spec{css})->attr($attr);
315 }
316 }
317  
318 sub _value_from_data {
319 70 ▶ my ($self, $data, %data_spec) = @_;
Subroutine _value_from_data: called CC=2 SCAR=6.9
320 70 my $value = $data->at(%data_spec)->value;
321 70 foreach my $filter (@{$data_spec{filters}}) {
322 10 $value = $self->_apply_data_filter($value, $data, $filter);
323 }
324 70 return $value;
325 }
326  
327 sub _apply_data_filter {
328 10 ▶ my ($self, $value, $data, $filter) = @_;
Subroutine _apply_data_filter: called CC=2 SCAR=6.9
329 10 my ($name, @args) = @$filter;
330 10 ▶ @args = map { ref $_ ? $self->_value_from_data($data, %$_) : $_ } @args;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 3 3 6
331 10 return $self->filter($name, $value, @args);
332 }
333  
334 sub _process_dom_filter {
335 1 ▶ my ($self, $dom, $data, $css, $cb) = @_;
Subroutine _process_dom_filter: called CC=2 SCAR=7.2
336 1 ▶ if($css eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($css eq '.') { } 0 1 1
337 0 $cb->($self, $dom, $data);
338 } else {
339 1 my $collection = $dom->find($css);
340 $collection->each(sub {
341 1 ▶ $cb->($self, $_, $data);
Subroutine __ANON__: called CC=1 SCAR=0.0
342 1 });
343 }
344 }
345  
346 sub _process_match_spec {
347 58 ▶ my ($self, $dom, $value, %match_spec) = @_;
Subroutine _process_match_spec: called CC=2 SCAR=6.9
348 58 ▶ if($match_spec{css} eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($match_spec{'css'} eq '.') { } 12 46 58
349 12 $self->_process_mode($dom, $value, %match_spec);
350 } else {
351 46 my $collection = $dom->find($match_spec{css});
352 $collection->each(sub {
353 48 ▶ $self->_process_mode($_, $value, %match_spec);
Subroutine __ANON__: called CC=1 SCAR=0.0
354 46 });
355 }
356 }
357  
358 sub _value_is_undef {
359 117 ▶ my ($self, $value) = @_;
Subroutine _value_is_undef: called CC=4 SCAR=13.9
360 117 ▶ return 1 if !defined($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 4 113 117
361 113 ▶ return 1 if Scalar::Util::blessed($value) && $value->isa('Template::Pure::UndefObject');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value) and $value->isa("Template::Pure::UndefObject") 1 112 113
Condition100%3/3
builtin::blessed($value) and $value->isa("Template::Pure::UndefObject")
!ll&&!rl&&r
90221
MC/DC100%2/2
builtin::blessed($value) and $value->isa("Template::Pure::UndefObject")
builtin::blessed($value) $value->isa("Template::Pure::UndefObject")
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $value->isa("Template::Pure::UndefObject")
ABresult
0X0
100
111
362 112 return 0;
363 }
364  
365  
366 sub _process_mode {
367 69 ▶ my ($self, $dom, $value, %match_spec) = @_;
Subroutine _process_mode: called CC=17 SCAR=29.3
368  
369 69 my $mode = $match_spec{mode};
370 69 my $target = $match_spec{target};
371 69 my $safe_value = $self->escape_html($value);
372  
373 ## This behavior may be tweaked in the future.
374 69 ▶ return $dom->remove if $self->_value_is_undef($safe_value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_value_is_undef($safe_value) 4 65 69
375  
376 65 ▶ if($mode eq 'replace') {
Branch: 3 branches
BranchTrueFalseTotal
if ($mode eq 'replace') { } 55 10 65
elsif ($mode eq 'append') { } 7 3 10
elsif ($mode eq 'prepend') { } 3 0 3
377 55 ▶ if($target eq 'content') {
Branch: 3 branches
BranchTrueFalseTotal
if ($target eq 'content') { } 43 12 55
elsif ($target eq 'node') { } 7 5 12
elsif (my $attr = $$target) { } 5 0 5
378 43 ▶ $dom->content($safe_value) unless $self->_value_is_undef($safe_value);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_value_is_undef($safe_value) 43 0 43
379 } elsif($target eq 'node') {
380 7 $dom->replace($safe_value);
381 } elsif(my $attr = $$target) {
382 5 $dom->attr($attr=>$safe_value);
383 } else {
384 0 die "Don't understand target of $target";
385 }
386 } elsif($mode eq 'append') {
387 7 ▶ if($target eq 'content') {
Branch: 3 branches
BranchTrueFalseTotal
if ($target eq 'content') { } 3 4 7
elsif ($target eq 'node') { } 2 2 4
elsif (my $attr = $$target) { } 2 0 2
388 3 $dom->append_content($safe_value);
389 } elsif($target eq 'node') {
390 2 $dom->append($safe_value);
391 } elsif(my $attr = $$target) {
392 2 ▶ my $current_attr = $dom->attr($attr)||'';
Condition100%2/2
$dom->attr($attr) || ''
l!l
11
MC/DC100%1/1
$dom->attr($attr) || ''
$dom->attr($attr)
Truth table100%2/2
A
A= $dom->attr($attr)
Aresult
11
00
393 2 $dom->attr($attr=>"$current_attr$safe_value" );
394 } else {
395 0 die "Don't understand target of $target";
396 }
397 } elsif($mode eq 'prepend') {
398 3 ▶ if($target eq 'content') {
Branch: 3 branches
BranchTrueFalseTotal
if ($target eq 'content') { } 1 2 3
elsif ($target eq 'node') { } 1 1 2
elsif (my $attr = $$target) { } 1 0 1
399 1 $dom->prepend_content($safe_value);
400 } elsif($target eq 'node') {
401 1 $dom->prepend($safe_value);
402 } elsif(my $attr = $$target) {
403 1 ▶ my $current_attr = $dom->attr($attr)||'';
Condition50%1/2
$dom->attr($attr) || ''
l!l
10
MC/DC0%0/1
$dom->attr($attr) || ''
$dom->attr($attr)
Truth table50%1/2
A
A= $dom->attr($attr)
Aresult
11
00
404 1 $dom->attr($attr=> "$safe_value$current_attr" );
405 } else {
406 0 die "Don't understand target of $target";
407 }
408 } else {
409 0 die "Not sure how to handle mode '$mode'";
410 }
411 }
412  
413 sub filter {
414 10 ▶ my ($self, $name, $data, @args) = @_;
Subroutine filter: called CC=2 SCAR=7.0
Pod documented
415 my %filters = (
416 $self->default_filters,
417 10 %{$self->{filters}}
418 );
419
420 10 ▶ my $filter = $filters{$name} ||
Condition50%1/2
$filters{$name} || die("Filter $name does not exist")
l!l
100
MC/DC0%0/1
$filters{$name} || die("Filter $name does not exist")
$filters{$name}
Truth table50%1/2
A
A= $filters{$name}
Aresult
11
00
421 die "Filter $name does not exist";
422
423 10 return $filter->($self, $data, @args);
424 }
425  
426 13 1;
427  
428 =head1 NAME
429  
430 Template::Pure - Perlish Port of pure.js
431  
432 =head1 SYNOPSIS
433  
434 use Template::Pure;
435  
436 my $html = q[
437 <html>
438 <head>
439 <title>Page Title</title>
440 </head>
441 <body>
442 <section id="article">
443 <h1>Header</h1>
444 <div>Story</div>
445 </section>
446 <ul id="friendlist">
447 <li>Friends</li>
448 </ul>
449 </body>
450 </html>
451 ];
452  
453 my $pure = Template::Pure->new(
454 template=>$html,
455 directives=> [
456 'head title' => 'meta.title',
457 '#article' => [
458 'h1' => 'header',
459 'div' => 'content',
460 ],
461 'ul li' => {
462 'friend<-user.friends' => [
463 '.' => '={friend}, #={i.index}',
464 ],
465 },
466 ],
467 );
468  
469 my $data = +{
470 meta => {
471 title => 'Travel Poetry',
472 created_on => '1/1/2000',
473 },
474 header => 'Fire',
475 content => q[
476 Are you doomed to discover that you never recovered from the narcoleptic
477 country in which you once stood? Where the fire's always burning, but
478 there's never enough wood?
479 ],
480 user => {
481 name => 'jnap',
482 friends => [qw/jack jane joe/],
483 },
484 };
485  
486 print $pure->render($data);
487  
488 Results in:
489  
490 <html>
491 <head>
492 <title>Travel Poetry</title>
493 </head>
494 <body>
495 <section id="article">
496 <h1>Fire</h1>
497 <div>
498 Are you doomed to discover that you never recovered from the narcoleptic
499 country in which you once stood? Where the fire&#39;s always burning, but
500 there&#39;s never enough wood?
501 </div>
502 </section>
503 <ul id="friendlist">
504 <li>jack, #1</li>
505 <li>jane, #2</li>
506 <li>joe, #3</li>
507 </ul>
508 </body>
509 </html>
510  
511 =head1 DESCRIPTION
512  
513 B<NOTE> WARNING: Early access module. Although we have a lot of test cases and this is the
514 third redo of the code I've not well tested certain features (such as using an object as
515 a data context) and other parts such as the way we handle undefined values (or empty
516 iterators) are still 'first draft'. Code currently is entirely unoptimized. Additionally the
517 documenation could use another detailed review, and we'd benefit from some 'cookbook' style docs.
518 Nevertheless its all working well enough that I'd like to publish it so I can start using it
519 more widely and hopefully some of you will like what you see and be inspired to try and help
520 close the gaps.
521  
522 L<Template::Pure> HTML/XML Templating system, inspired by pure.js L<http://beebole.com/pure/>, with
523 some additions and modifications to make it more Perlish and to be more suitable
524 as a server side templating framework for larger scale needs instead of single page
525 web applications.
526  
527 The core concept is you have your templates in pure HTML and create CSS style
528 matches to run transforms on the HTML to populate data into the template. This allows you
529 to have very clean, truely logicless templates. This approach can be useful when the HTML designers
530 know little more than HTML and related technologies. It helps promote separation of concerns
531 between your UI developers and your server side developers. Over the long term the separate
532 and possibilities for code reuse can lead to an easier to maintain system.
533  
534 The main downside is that it can place more work on the server side developers, who have to
535 write the directives unless your UI developers are able and willing to learn the minimal Perl
536 required for that job. Also since the CSS matching directives can be based on the document
537 structure, it can lead to onerous tight binding between yout document structure and the layout/display
538 logic. For example due to some limitations in the DOM parser, you might have to add some extra markup
539 just so you have a place to match, when you have complex and deeply nested data.
540  
541 Additionally many UI designers already are familiar with some basic templating systems and
542 might really prefer to use that so that they can maintain more autonomy and avoid the additional
543 learning curve that L<Template::Pure> will requires (most people seem to find its a bit more
544 effort to learn off the top compared to more simple systems like Mustache or even L<Template::Toolkit>.
545  
546 Although inspired by pure.js L<http://beebole.com/pure/> this module attempts to help mitigate some
547 of the listed possible downsides with additional features that are a superset of the original
548 pure.js specification. For example you may include templates inside of templates as includes or even
549 overlays that provide much of the same benefit that template inheritance offers in many other
550 popular template frameworks. These additional features are intended to make it more suitable as a general
551 purpose server side templating system.
552  
553 =head1 CREATING TEMPLATE OBJECTS
554  
555 The first step is to create a L<Template::Pure> object:
556  
557 my $pure = Template::Pure->new(
558 template=>$html,
559 directives=> \@directives);
560  
561 L<Template::Pure> has two required parameters:
562  
563 =over 4
564  
565 =item template
566  
567 This is a string that is an HTML template that can be parsed by L<DOM::Tiny>
568  
569 =item directives
570  
571 An arrayref of directives, which are commands used to transform the template when
572 rendering against data. For more on directives, see L</DIRECTIVES>
573  
574 =back
575  
576 L<Template::Pure> has a third optional parameter, 'filters', which is a hashref of
577 user created filters. For more see L<Template::Pure::Filters> and L</FILTERS>.
578  
579 Once you have a created object, you may call the following methods:
580  
581 =over 4
582  
583 =item render ($data, ?\@extra_directives?)
584  
585 Render a template with the given '$data', which may be a hashref or an object with
586 fields that match data paths defined in the directions section (see L</DIRECTIVES>)
587  
588 Returns a string. You may pass in an arrayref of extra directives, which are executed
589 just like directives defined at instantiation time (although future versions of this
590 distribution may offer optimizations to directives known at create time). These optional
591 added directives are executed after the directives defined at create time.
592  
593 Since we often traverse the $data structure as part of rendering a template, we usually call
594 the current path the 'data context'. We always track the base or root context and you can
595 always return to it, as you will later see in the L</DIRECTIVES> section.
596  
597 =item process_dom ($data, ?\@extra_directives?)
598  
599 Works just like 'render', except we return a L<DOM::Tiny> object instead of a string directly.
600 Useful if you wish to retrieve the L<DOM::Tiny> object for advanced, custom tranformations.
601  
602 =item data_at_path ($data, $path)
603  
604 Given a $data object, returns the value at the defined $path. Useful in your coderef actions
605 (see below) when you wish to grab data from the current data context but wish to avoid
606 using $data implimentation specific lookup.
607  
608 =item escape_html ($string)
609  
610 Given a string, returns a version of it that has been properly HTML escaped. Since we do
611 such escaping automatically for most directives you won't need it a lot, but could be useful
612 in a coderef action. Can also be called as a filter (see L</FILTERS>).
613  
614 =item encoded_string ($string)
615  
616 As mentioned we automatically escape values to help protect you against HTML injection style
617 attacked, but there might be cases when you don't wish this protection. Can also be called
618 as a filter (see L</FILTERS>).
619  
620 =back
621  
622 There are other methods in the code but please consider all that stuff part of my 'black box'
623 and only reach into it if you are willing to suffer possible breakage on version changes.
624  
625 =head1 DIRECTIVES
626  
627 Directives are instructions you prepare against a template, upon which later we render
628 data against. Directives are ordered and are excuted in the order defined. The general
629 form of a directive is C<CSS Match> => C<Action>, where action can be a path to fetch data
630 from, more directives, a coderef, etc. The main idea is that the CSS matches
631 a node in the HTML template, and an 'action' is performed on that node. The following actions are allowed
632 against a match specification:
633  
634 =head2 Scalar - Replace the value indicated by the match.
635  
636 my $html = qq[
637 <div>
638 Hello <span id='name'>John Doe</span>!
639 </div>
640 ];
641  
642 my $pure = Template::Pure->new(
643 template => $html,
644 directives => [
645 '#name' => 'fullname',
646 ]);
647  
648 my %data = (
649 fullname => 'H.P Lovecraft');
650  
651 print $pure->render(\%data);
652  
653 Results in:
654  
655 <div>
656 Hello <span id='name'>H.P Lovecraft</span>!
657 </div>
658  
659 In this simple case the value of the CSS match '#name' is replaced by the value 'fullname'
660 indicated at the current data context (as you can see the starting context is always the
661 root, or top level data object.)
662  
663 If instead of a hashref the rendered data context is an object, we look for a method
664 matching the name of the indicated path. If there is no matching method or key, we generate
665 an exception.
666  
667 If there is a key matching the requested data path as indicated by the directive, but the associated
668 value is undef, then the matching node (tag included) is removed. If there is no matching key,
669 this raises an error.
670  
671 B<NOTE>: Remember that you can use dot notation in your action value to indicate a path on the
672 current data context, for example:
673  
674 my %data = (
675 identity => {
676 first_name => 'Howard',
677 last_name => 'Lovecraft',
678 });
679  
680 my $pure = Template::Pure->new(
681 template => $html,
682 directives => [ '#last_name' => 'identity.last_name']
683 );
684  
685 In this case the value of the node indicated by '#last_name' will be set to 'Lovecraft'.
686  
687 =head2 ScalarRef - Set the value to the results of a match
688  
689 There may be times when you want to set the value of something to an existing
690 value in the current template:
691  
692 my $html = qq[
693 <html>
694 <head>
695 <title>Welcome Page</title>
696 </head>
697 <body>
698 <h1>Page Title</h1>
699 </body>
700 </html>
701 ];
702  
703 my $pure = Template::Pure->new(
704 template = $html,
705 directives => [
706 'h1#title' => \'/title',
707 ]);
708  
709 print $pure->render({});
710  
711 Results in:
712  
713 <html>
714 <head>
715 <title>Welcome Page</title>
716 </head>
717 <body>
718 <h1>Welcome Page</h1>
719 </body>
720 </html>
721  
722 B<NOTE> Since directives are processed in order, this means that you can
723 reference the rendered value of a previous directive via this alias.
724  
725 B<NOTE> The match runs against the current selected node, as defined by the last
726 successful match. If you need to match a value from the root of the DOM tree you
727 can use the special '/' syntax on your CSS match, as shown in the above example,
728 or:
729  
730 directives => [
731 'h1#title' => \'/title',
732 ]);
733  
734  
735 =head2 Coderef - Programmatically replace the value indicated
736  
737 my $html = qq[
738 <div>
739 Hello <span id='name'>John Doe</span>!
740 </div>
741 ];
742  
743 my $pure = Template::Pure->new(
744 template => $html,
745 directives => [
746 '#name' => sub {
747 my ($instance, $dom, $data) = @_;
748 return $data->{id}{first_name} .' '. $data->{id}{first_name};
749 },
750 ]
751 );
752  
753 my %data = (
754 id => {
755 first_name => 'Howard',
756 last_name => 'Lovecraft',
757 });
758  
759 print $pure->render(\%data);
760  
761  
762 Results in:
763  
764 <div>
765 Hello <span id='name'>Howard Lovecraft</span>!
766 </div>
767  
768 For cases where the display logic is complex, you may use an anonymous subroutine to
769 provide the matched value. This anonymous subroutine receives the following three
770 arguments:
771  
772 $instance: The template instance
773 $dom: The DOM Node at the current match (as a L<DOM::Tiny> object).
774 $data: Data reference at the current context.
775  
776 Your just need to return the value desired which will substitute for the matched node's
777 current value.
778  
779 B<NOTE>: It might be a good idea to try and maintain as much implementation independence
780 from you $data model as possible. That way if later you change your $data from a hashref
781 to an instance of an object you won't break your code. One way to help achieve this is
782 to use L<Template::Pure>'s data lookup helper methods (which support dot notation and more
783 as described below. For example consider re-writing the above example like this:
784  
785 my $pure = Template::Pure->new(
786 template => $html,
787 directives => [
788 '#name' => sub {
789 my ($instance, $dom, $data) = @_;
790 return $instance->data_at_path($data, 'id.first_name') .' '.
791 $instance->data_at_path($data, 'id.last_name') ;
792 },
793 ]
794 );
795  
796 =head2 Arrayref - Run directives under a new DOM root
797  
798 Somtimes its handy to group a set of directives under a given node. For example:
799  
800 my $html = qq[
801 <dl id='contact'>
802 <dt>Phone</dt>
803 <dd class='phone'>(xxx) xxx-xxxx</dd>
804 <dt>Email</dt>
805 <dd class='email'>aaa@email.com</dd>
806 </dl>
807 ];
808  
809 my $pure = Template::Pure->new(
810 template = $html,
811 directives => [
812 '#contact' => [
813 '.phone' => 'contact.phone',
814 '.email' => 'contact.email',
815 ],
816 );
817  
818 my %data = (
819 contact => {
820 phone => '(212) 387-9509',
821 email => 'jjnapiork@cpan.org',
822 }
823 );
824  
825 print $pure->render(\%data);
826  
827 Results in:
828  
829 <dl id='contact'>
830 <dt>Phone</dt>
831 <dd class='phone'>(212) 387-9509</dd>
832 <dt>Email</dt>
833 <dd class='email'>jjnapiork@cpan.org'</dd>
834 </dl>
835  
836 For this simple case you could have made it more simple and avoided the nested directives, but
837 in a complex template with a lot of organization you might find this leads to more readable and
838 concise directives. It can also promote reusability.
839  
840 =head2 Hashref - Move the root of the Data Context
841  
842 Just like it may be valuable to move the root DOM context to an inner node, sometimes you'd
843 like to move the root of the current Data context to an inner path point. This can result in cleaner
844 templates with less repeated syntax, as well as promote reusability. In order to do this you
845 use a Hashref whose key is the path under the data context you wish to move to and who's value
846 is an Arrayref of new directives. These new directives can be any type of directive as already
847 shown or later documented.
848  
849 my $html = qq[
850 <dl id='contact'>
851 <dt>Phone</dt>
852 <dd class='phone'>(xxx) xxx-xxxx</dd>
853 <dt>Email</dt>
854 <dd class='email'>aaa@email.com</dd>
855 </dl>
856 ];
857  
858 my $pure = Template::Pure->new(
859 template => $html,
860 directives => [
861 '#contact' => {
862 'contact' => [
863 '.phone' => 'phone',
864 '.email' => 'email',
865 ],
866 },
867 ]
868 );
869  
870 my %data = (
871 contact => {
872 phone => '(212) 387-9509',
873 email => 'jjnapiork@cpan.org',
874 }
875 );
876  
877 print $pure->render(\%data);
878  
879 Results in:
880  
881 <dl id='contact'>
882 <dt>Phone</dt>
883 <dd class='phone'>(212) 387-9509</dd>
884 <dt>Email</dt>
885 <dd class='email'>jjnapiork@cpan.org'</dd>
886 </dl>
887  
888 In addition to an arrayref of new directives, you may assign the new DOM and Data context
889 directly to a template object (see L</Object - Set the match value to another Pure Template>
890 For example:
891  
892 my $contact_include = Template::Pure->new(
893 template => q[
894 <dl>
895 <dt>Name</dt>
896 <dd class='name'>First Last</dd>
897 <dt>Email</dt>
898 <dd class='email'>Email@email.com</dd>
899 </dl>
900 ],
901 directives => [
902 '.name' => 'fullname',
903 '.email' => 'email',
904  
905  
906 my $pure = Template::Pure->new(
907 template => $html,
908 directives => [
909 '#contact' => {
910 'contact' => $contact_include;
911 },
912 ]
913 );
914  
915 print $pure->render({
916 person => {
917 contact => {
918 fullname => 'John Doe',
919 email => 'jd@email.com'.
920 }
921 },
922 });
923  
924 This lets you isolate the data structure of your includes to improve reuse and clarity.
925  
926 =head2 Hashref - Create a Loop
927  
928 Besides moving the current data context, setting the value of a match spec key to a
929 hashref can be used to perform loops over a node, such as when you wish to create
930 a list:
931  
932 my $html = qq[
933 <ol>
934 <li class='name'>
935 <span class='first-name'>John</span>
936 <span class='last-name'>Doe</span>
937 </li>
938 </ol>
939 ];
940  
941 my $pure = Template::Pure->new(
942 template => $html,
943 directives => [
944 '#name' => {
945 'name<-names' => [
946 '.first-name' => 'name.first',
947 '.last-name' => 'name.last',
948 ],
949 },
950 ]
951 );
952  
953 my %data = (
954 names => [
955 {first => 'Mary', last => 'Jane'},
956 {first => 'Jared', last => 'Prex'},
957 {first => 'Lisa', last => 'Dig'},
958 ]
959 );
960  
961 print $pure->render(\%data);
962  
963 Results in:
964  
965 <ol id='names'>
966 <li class='name'>
967 <span class='first-name'>Mary</span>
968 <span class='last-name'>Jane</span>
969 </li>
970 <li class='name'>
971 <span class='first-name'>Jared</span>
972 <span class='last-name'>Prex</span>
973 </li>
974 <li class='name'>
975 <span class='first-name'>Lisa</span>
976 <span class='last-name'>Dig</span>
977 </li>
978 </ol>
979  
980 The indicated data path must be either an ArrayRef, a Hashref, or an object that provides
981 an iterator interface (see below).
982  
983 For each item in the array we render the selected node against that data and
984 add it to parent node. So the originally selected node is completely replaced by a
985 collection on new nodes based on the data. Basically just think you are repeating over the
986 node value for as many times as there is items of data.
987  
988 In the case the referenced data is explicitly set to undefined, the full node is
989 removed (the matched node, not just the value).
990  
991 =head3 Special value injected into a loop
992  
993 When you create a loop we automatically add a special data key called 'i' which is an object
994 that contains meta data on the current state of the loop. Fields that can be referenced are:
995  
996 =over 4
997  
998 =item current_value
999  
1000 An alias to the current value of the iterator.
1001  
1002 =item index
1003  
1004 The current index of the iterator (starting from 1.. or from the first key in a hashref or fields
1005 interator).
1006  
1007 =item max_index
1008  
1009 The last index item, either number or field based.
1010  
1011 =item count
1012  
1013 The total number of items in the iterator (as a number, starting from 1).
1014  
1015 =item is_first
1016  
1017 Is this the first item in the loop?
1018  
1019 =item is_last
1020  
1021 Is this the last item in the loop?
1022  
1023 =item is_even
1024  
1025 Is this item 'even' in regards to its position (starting with position 2 (the first position, or also
1026 known as index '1') being even).
1027  
1028 =item is_odd
1029  
1030 Is this item 'even' in regards to its position (starting with position 1 (the first position, or also
1031 known as index '0') being odd).
1032  
1033 =back
1034  
1035 =head3 Looping over a Hashref
1036  
1037 You may loop over a hashref as in the following example:
1038  
1039 my $html = qq[
1040 <dl id='dlist'>
1041 <section>
1042 <dt>property</dt>
1043 <dd>value</dd>
1044 </section>
1045 </dl>];
1046  
1047 my $pure = Template::Pure->new(
1048 template => $html,
1049 directives => [
1050 'dl#dlist section' => {
1051 'property<-author' => [
1052 'dt' => 'i.index',
1053 'dd' => 'property',
1054 ],
1055 },
1056 ]
1057 );
1058  
1059 my %data = (
1060 author => {
1061 first_name => 'John',
1062 last_name => 'Napiorkowski',
1063 email => 'jjn1056@yahoo.com',
1064 },
1065 );
1066  
1067 print $pure->render(\%data);
1068  
1069 Results in:
1070  
1071 <dl id="dlist">
1072 <section>
1073 <dt>first_name</dt>
1074 <dd>John</dd>
1075 </section>
1076 <section>
1077 <dt>last_name</dt>
1078 <dd>Napiorkowski</dd>
1079 </section>
1080 <section>
1081 <dt>email</dt>
1082 <dd>jjn1056@yahoo.com</dd>
1083 </section>
1084 </dl>
1085  
1086 B<NOTE> This is a good example of a current limitation in the CSS Match Specification that
1087 requires adding a 'section' tag as a fudge to give the look something to target. Future
1088 versions of this distribution may offer additional match syntax to get around this problem.
1089  
1090 B<NOTE> Notice the usage of the special data path 'i.index' which for a hashref or fields
1091 type loop contains the field or hashref key name.
1092  
1093 B<NOTE> Please remember that in Perl Hashrefs are not ordered. If you wish to order your
1094 Hashref based loop please see L</Sorting and filtering a Loop> below.
1095  
1096 =head3 Iterating over an Object
1097  
1098 If the value indicated by the required path is an object, we need that object to provide
1099 an interface indicating if we should iterate like an ArrayRef (for example a L<DBIx::Class::ResultSet>
1100 which is a collection of database rows) or like a HashRef (for example a L<DBIx::Class>
1101 result object which is one row in the returned database query consisting of field keys
1102 and associated values).
1103  
1104 =head4 Objects that iterate like a Hashref
1105  
1106 The object should provide a method called 'display_fields' (which can be overridden with
1107 the key 'display_fields_handler', see below) which should return a list of methods that are used
1108 as 'keys' to provide values for the iterator. Each method return represents one item
1109 in the loop.
1110  
1111 =head4 Objects that iterate like an ArrayRef
1112  
1113 Your object should defined the follow methods:
1114  
1115 =over 4
1116  
1117 =item next
1118  
1119 Returns the next item in the iterator or undef if there are no more items
1120  
1121 =item count
1122  
1123 The number of items in the iterator (counting from 1 for one item)
1124  
1125 =item reset
1126  
1127 Reset the iterator to the starting item.
1128  
1129 =item all
1130  
1131 Returns all the items in the iterator
1132  
1133 =back
1134  
1135 =head3 Sorting and filtering a Loop
1136  
1137 You may provide a custom anonymous subroutine to provide a display
1138 specific order to your loop. For simple values such as Arrayrefs
1139 and hashrefs this is simple:
1140  
1141 my $html = qq[
1142 <ol id='names'>
1143 <li class='name'>
1144 <span class='first-name'>John</span>
1145 <span class='last-name'>Doe</span>
1146 </li>
1147 </ol>
1148 ];
1149  
1150 my $pure = Template::Pure->new(
1151 template = $html,
1152 directives => [
1153 '#name' => {
1154 'name<-names' => [
1155 '.first-name' => 'name.first',
1156 '.last-name' => 'name.last',
1157 ],
1158 'order_by' => sub {
1159 my ($hashref, $a, $b) = @_;
1160 return $a->{last} cmp $b->{last};
1161 },
1162 },
1163 ]
1164 );
1165  
1166 my %data = (
1167 names => [
1168 {first => 'Mary', last => 'Jane'},
1169 {first => 'Jared', last => 'Prex'},
1170 {first => 'Lisa', last => 'Dig'},
1171 ]
1172 );
1173  
1174 print $pure->render(\%data);
1175  
1176 Results in:
1177  
1178 <ol id='names'>
1179 <li class='name'>
1180 <span class='first-name'>Lisa</span>
1181 <span class='last-name'>Dig</span>
1182 </li>
1183 <li class='name'>
1184 <span class='first-name'>Mary</span>
1185 <span class='last-name'>Jane</span>
1186 </li>
1187 <li class='name'>
1188 <span class='first-name'>Jared</span>
1189 <span class='last-name'>Prex</span>
1190 </li>
1191 </ol>
1192  
1193 So you have a key 'order_by' at the same level as the loop action declaration
1194 which is an anonynous subroutine that takes three arguments, the first being
1195 a reference to the data you are sorting (an arrayref or hashref)
1196 followed by the $a and $b items to be compared for example as in:
1197  
1198 my @display = sort { $a->{last} cmp $b->{last} } @list;
1199  
1200 If your iterator is over an object the interface is slightly more complex since
1201 we allow for the object to provide a sort method based on its internal needs.
1202 For example if you have a L<DBIx::Class::Resultset> as your iterator, you may
1203 wish to order your display at the database level:
1204  
1205 'sort' => sub {
1206 my ($object) = @_;
1207 return $object->order_by_last_name;
1208 },
1209  
1210 We recommend avoiding implimentation specific details when possible (for example
1211 in L<DBIx::Class> use a custom resultset method, not a ->search query.).
1212  
1213 =head3 Perform a 'filter' on your loop items
1214  
1215 You may wish for the purposes of display to skip items in your loop. Similar to
1216 'order_by', you may create a 'grep' key that returns either true or false to determine
1217 if an item in the loop is allowed (works like the 'grep' function).
1218  
1219 # Only show items where the value is greater than 10.
1220 'filter' => sub {
1221 my ($template, $item) = @_;
1222 return $item > 10;
1223 },
1224  
1225 Just like with 'order_by', if your iterator is over an object, you recieve that
1226 object as the argument and are expected to return a new iterator that is properly
1227 filtered:
1228  
1229 'grep' => sub {
1230 my ($template, $iterator) = @_;
1231 return $iterator->only_over_10;
1232 },
1233  
1234 =head3 Generating display_fields
1235  
1236 When you are iterating over an object that is like a Hashref, you need
1237 to inform us of how to get the list of field names which should be the
1238 names of methods on your object who's value you wish to display. By default
1239 we look for a method called 'display fields' but you can customize this
1240 in one of two ways. You can set a key 'display_fields' to be the name of
1241 an alternative method:
1242  
1243 directives => [
1244 '#meta' => {
1245 'field<-info' => [
1246 '.name' => 'field.key',
1247 '.value' => 'field.value',
1248 ],
1249 'display_fields' => 'columns',
1250 },
1251 ]
1252  
1253 =head2 Object - Set the match value to another Pure Template
1254  
1255 my $section_html = qq[
1256 <div>
1257 <h2>Example Section Title</h2>
1258 <p>Example Content</p>
1259 </div>
1260 ];
1261  
1262 my $pure_section = Template::Pure->new(
1263 template = $section_html,
1264 directives => [
1265 'h2' => 'title',
1266 'p' => 'story'
1267 ]);
1268  
1269 my $html = qq[
1270 <div class="story">Example Content</div>
1271 ];
1272  
1273 my $pure = Template::Pure->new(
1274 template = $html,
1275 directives => [
1276 'div.story' => $pure_section,
1277 ]);
1278  
1279 my %data = (
1280 title => 'The Supernatural in Literature',
1281 story => $article_text,
1282 );
1283  
1284 print $pure->render(\%data);
1285  
1286 Results in:
1287  
1288 <div class="story">
1289 <div>
1290 <h2>The Supernatural in Literature</h2>
1291 <p>$article_text</p>
1292 </div>
1293 </div>
1294  
1295 When the action is an object it must be an object that conformation
1296 to the interface and behavior of a L<Template::Pure> object. For the
1297 most part this means it must be an object that does a method 'render' that
1298 takes the current data context refernce and returns an HTML string suitable
1299 to become that value of the matched node.
1300  
1301 When encountering such an object we pass the current data context, but we
1302 add one additional field called 'content' which is the value of the matched
1303 node. You can use this so that you can 'wrap' nodes with a template (similar
1304 to the L<Template> WRAPPER directive).
1305  
1306 my $wrapper_html = qq[
1307 <p class="headline">To Be Wrapped</p>
1308 ];
1309  
1310 my $wrapper = Template::Pure->new(
1311 template = $wrapper_html,
1312 directives => [
1313 'p.headline' => 'content',
1314 ]);
1315  
1316 my $html = qq[
1317 <div>This is a test of the emergency broadcasting
1318 network... This is only a test</div>
1319 ];
1320  
1321 my $wrapper = Template::Pure->new(
1322 template = $html,
1323 directives => [
1324 'div' => $wrapper,
1325 ]);
1326  
1327 Results in:
1328  
1329 <div>
1330 <p class="headline">This is a test of the emergency broadcasting
1331 network... This is only a test</p>
1332 </div>
1333  
1334 Lastly you can mimic a type of inheritance using data mapping and
1335 node aliasing:
1336  
1337 my $master_html = q[
1338 <html>
1339 <head>
1340 <title>Example Title</title>
1341 <link rel="stylesheet" href="/css/pure-min.css"/>
1342 <link rel="stylesheet" href="/css/grids-responsive-min.css"/>
1343 <link rel="stylesheet" href="/css/common.css"/>
1344 <script src="/js/3rd-party/angular.min.js"></script>
1345 <script src="/js/3rd-party/angular.resource.min.js"></script>
1346 </head>
1347 <body>
1348 <section id="content">...</section>
1349 <p id="foot">Here's the footer</p>
1350 </body>
1351 </html>
1352 ];
1353  
1354 my $master = Template::Pure->new(
1355 template=>$master_html,
1356 directives=> [
1357 'title' => 'title',
1358 '^title+' => 'scripts',
1359 'body section#content' => 'content',
1360 ]);
1361  
1362 my $page_html = q[
1363 <html>
1364 <head>
1365 <title>The Real Page</title>
1366 <script>
1367 function foo(bar) {
1368 return baz;
1369 }
1370 </script>
1371 </head>
1372 <body>
1373 You are doomed to discover that you never
1374 recovered from the narcolyptic country in
1375 which you once stood; where the fire's always
1376 burning but there's never enough wood.
1377 </body>
1378 </html>
1379 ];
1380  
1381 my $page = Template::Pure->new(
1382 template=>$page_html,
1383 directives=> [
1384 'title' => 'meta.title',
1385 'html' => [
1386 {
1387 title => \'title',
1388 scripts => \'^head script',
1389 content => \'body',
1390 },
1391 '^.' => $master,
1392 ]
1393 ]);
1394  
1395 my $data = +{
1396 meta => {
1397 title => 'Inner Stuff',
1398 },
1399 };
1400  
1401 Results in:
1402  
1403 <html>
1404 <head>
1405 <title>Inner Stuff</title><script>
1406 function foo(bar) {
1407 return baz;
1408 }
1409 </script>
1410 <link href="/css/pure-min.css" rel="stylesheet">
1411 <link href="/css/grids-responsive-min.css" rel="stylesheet">
1412 <link href="/css/common.css" rel="stylesheet">
1413 <script src="/js/3rd-party/angular.min.js"></script>
1414 <script src="/js/3rd-party/angular.resource.min.js"></script>
1415 </head>
1416 <body>
1417 <section id="content">
1418 You are doomed to discover that you never
1419 recovered from the narcolyptic country in
1420 which you once stood; where the fire&amp;#39;s always
1421 burning but there&amp;#39;s never enough wood.
1422 </section>
1423 <p id="foot">Here&#39;s the footer</p>
1424 </body>
1425 </html>
1426  
1427 =head2 Object - Any Object that does 'TO_HTML'
1428  
1429 In addition to using a L<Template::Pure> object as the target action for
1430 a match specification, you may use any object that does a method called
1431 'TO_HTML'. Such a method would expect to recieve the current template
1432 object, the current matched DOM, and the current value of the Data context
1433 as arguments. It should return a string that is used as the replacement
1434 value for the given match specification. For example:
1435  
1436 {
1437 package Local::Example;
1438  
1439 sub new {
1440 my ($class, %args) = @_;
1441 return bless \%args, $class;
1442 }
1443  
1444 sub TO_HTML {
1445 my ($self, $pure, $dom, $data) = @_;
1446 return $dom->attr('class');
1447 }
1448 }
1449  
1450 my $html = q[
1451 <html>
1452 <head>
1453 <title>Page Title</title>
1454 </head>
1455 <body>
1456 <p class="foo">aaa</a>
1457 <p class="bar">bbb</a>
1458 </body>
1459 </html>
1460 ];
1461  
1462 my $pure = Template::Pure->new(
1463 template=>$html,
1464 directives=> [
1465 'title' => 'title',
1466 'p' => Local::Example->new,
1467 ]);
1468  
1469 my $data = +{
1470 title => 'A Shadow Over Innsmouth',
1471 };
1472  
1473 print $pure->render($data);
1474  
1475 Results in:
1476  
1477 <html>
1478 <head>
1479 <title>A Shadow Over Innsmouth</title>
1480 </head>
1481 <body>
1482 <p class="foo">foo</p>
1483 <p class="bar">bar</p>
1484 </body>
1485 </html>
1486  
1487 =head2 Using Dot Notation in Directive Data Mapping
1488  
1489 L<Template::Pure> allows you to indicate a path to a point in your
1490 data context using 'dot' notation, similar to many other template
1491 systems such as L<Template>. In general this offers an abstraction
1492 that smooths over the type of reference your data is (an object, or
1493 a hashref) such as to make it easier to swap the type later on as
1494 needs grow, or for testing:
1495  
1496 directives => [
1497 'title' => 'meta.title',
1498 'copyright => 'meta.license_info.copyright_date',
1499 ...,
1500 ],
1501  
1502 my %data = (
1503 meta => {
1504 title => 'Hello World!',
1505 license_info => {
1506 type => 'Artistic',
1507 copyright_date => 2016,
1508 },
1509 },
1510 );
1511  
1512 Basically you use '.' to replace '->' and we figure out if the path
1513 is to a key in a hashref or method on an object for you.
1514  
1515 In the case when the value of a path is explictly undefined, the behavior
1516 is to remove the matching node (the full matching node, not just the value).
1517  
1518 Trying to resolve a key or method that does not exist returns an error.
1519 However its not uncommon for some types of paths to have optional parts
1520 and in these cases its not strictly and error when the path does not exist.
1521 In this case you may prefix 'optional:' to your path part, which will surpress
1522 an error in the case the requested path does not exist:
1523  
1524 directives => [
1525 'title' => 'meta.title',
1526 'copyright => 'meta.license_info.optional:copyright_date',
1527 ...,
1528 ],
1529  
1530 In this case instead of returning an error we treat the path as though it
1531 returned 'undefined' (which means we trim out the matching node).
1532  
1533 In other cases your path might exist, but returns undefined. This can be an
1534 issue if you have following paths (common case when traversing L<DBIx::Class>
1535 relationships...) and you don't want to throw an exception. In this case you
1536 may use a 'maybe:' prefix, which returns undefined and treats the entire remaining
1537 path as undefined:
1538  
1539 directives => [
1540 'title' => 'meta.title',
1541 'copyright => 'meta.maybe:license_info.copyright_date',
1542 ...,
1543 ],
1544  
1545 =head2 Remapping Your Data Context
1546  
1547 If the first element of your directives (either at the root of the directives
1548 or when you create a new directives list under a given node) is a hashref
1549 we take that as special instructions to remap the current data context to
1550 a different structure. Useful for increase reuse and decreasing complexity
1551 in some situations:
1552  
1553 my $html = qq[
1554 <dl id='contact'>
1555 <dt>Phone</dt>
1556 <dd class='phone'>(xxx) xxx-xxxx</dd>
1557 <dt>Email</dt>
1558 <dd class='email'>aaa@email.com</dd>
1559 </dl>
1560 ];
1561  
1562 my $pure = Template::Pure->new(
1563 template = $html,
1564 directives => [
1565 '#contact' => [
1566 {
1567 phone => 'contact.phone',
1568 email => 'contact.email,
1569 }, [
1570 '.phone' => 'phone',
1571 '.email' => 'email',
1572 ],
1573 },
1574 ]
1575 );
1576  
1577 my %data = (
1578 contact => {
1579 phone => '(212) 387-9509',
1580 email => 'jjnapiork@cpan.org',
1581 }
1582 );
1583  
1584 print $pure->render(\%data);
1585  
1586 Results in:
1587  
1588 <dl id='contact'>
1589 <dt>Phone</dt>
1590 <dd class='phone'>(212) 387-9509</dd>
1591 <dt>Email</dt>
1592 <dd class='email'>jjnapiork@cpan.org'</dd>
1593 </dl>
1594  
1595 =head2 Using Placeholders in your Actions
1596  
1597 Sometimes it makes sense to compose your replacement value of several
1598 bits of information. Although you could do this with lots of extra 'span'
1599 tags, sometimes its much more clear and brief to put it all together. For
1600 example:
1601  
1602 my $pure = Template::Pure->new(
1603 template => $html,
1604 directives => [
1605 '#content' => 'Hi ={name}, glad to meet you on=#{today}',
1606 ]
1607 );
1608  
1609 In the case your value does not refer itself to a path, but instead contains
1610 one or more placeholders which are have data paths inside them. These data
1611 paths can be simple or complex, and even contain filters:
1612  
1613 my $pure = Template::Pure->new(
1614 template => $html,
1615 directives => [
1616 '#content' => 'Hi ={name | uc}, glad to meet you on ={today}',
1617 ]
1618 );
1619  
1620 For more on filters see L</FILTERS>
1621  
1622 =head2 Special indicators in your match.
1623  
1624 In General your match specification is a CSS match supported by the
1625 underlying HTML parser. However the following specials are supported
1626 for needs unique to the needs of templating:
1627  
1628 =over 4
1629  
1630 =item '.': Select the current node
1631  
1632 Used to indicate the current root node. Useful when you have created a match
1633 with sub directives.
1634  
1635 my $pure = Template::Pure->new(
1636 template => $html,
1637 directives => [
1638 'body' => [
1639 ]
1640 ]
1641 );
1642  
1643 =item '/': The root node
1644  
1645 Used when you which to select from the root of the template DOM, not the current
1646 selected node.
1647  
1648 =item '@': Select an attribute within the current node
1649  
1650 Used to update values inside a node:
1651  
1652 my $pure = Template::Pure->new(
1653 template => $html,
1654 directives => [
1655 'h1@class' => 'header_class',
1656 ],
1657 );
1658  
1659 =item '+': Append or prepend a value
1660  
1661 my $pure = Template::Pure->new(
1662 template => $html,
1663 directives => [
1664 '+h1' => 'title',
1665 '#footer+' => 'copyright_date',
1666 ],
1667 );
1668  
1669 The default behavior is for a match to replace the matched node's content. In some
1670 cases you may wish to preserve the template content and instead either add more
1671 content to the front or back of it.
1672  
1673 B<NOTE> Can be combined with '@' to append / prepend to an attribute.
1674  
1675 B<NOTE> Special handling when appending or prepending to a class attribute (we add a
1676 space if there is an existing since that is expected).
1677  
1678 =item '^': Replace current node completely
1679  
1680 Normally we replace, append or prepend to the value of the selected node. Using the
1681 '^' at the front of your match indicates operation should happen on the entire node,
1682 not just the value. Can be combined with '+' for append/prepend.
1683  
1684 =item '|': Run a filter on the current node
1685  
1686 Passed the currently selected node to a code reference. You can run L<DOM::Tiny>
1687 transforms on the entire selected node. Nothing should be returned from this
1688 coderef.
1689  
1690 'body|' => sub {
1691 my ($template, $dom, $data) = @_;
1692 $dom->find('p')->each( sub {
1693 $_->attr('data-pure', 1);
1694 });
1695 }
1696  
1697 =back
1698  
1699 =head1 FILTERS
1700  
1701 You may filter you data via a provided built in display filter:
1702  
1703 my $pure = Template::Pure->new(
1704 template => $html,
1705 directives => [
1706 '#content' => 'data.content | escape_html',
1707 ]
1708 );
1709  
1710 If a filter takes arguments you may fill those arguments with either literal
1711 values or a 'placeholder' which should point to a path in the current data
1712 context.
1713  
1714 my $pure = Template::Pure->new(
1715 template => $html,
1716 directives => [
1717 '#content' => 'data.content | repeat(#{times}) | escape_html',
1718 ]
1719 );
1720  
1721 You may add a custom filter when you define your template:
1722  
1723 my $pure = Template::Pure->new(
1724 filters => {
1725 custom_filter => sub {
1726 my ($template, $data, @args) = @_;
1727 # Do something with the $data, possible using @args
1728 # to control what that does
1729 return $data;
1730 },
1731 },
1732 );
1733  
1734 An example custom Filter:
1735  
1736 my $pure = Template::Pure->new(
1737 filters => {
1738 custom_filter => sub {
1739 my ($template, $data, @args) = @_;
1740 # TBD
1741 # return $data;
1742 },
1743 },
1744 );
1745  
1746 In general you can use filters to reduce the need to write your action as a coderef
1747 which should make it easier for you to give the job of writing directives / actions
1748 to non programmers.
1749  
1750 See L<Template::Pure::Filters> for all bundled filters.
1751  
1752 =head1 IMPORTANT NOTE REGARDING VALID HTML
1753  
1754 Please note that L<DOM::Tiny> tends to enforce rule regarding valid HTML5. For example, you
1755 cannot nest a block level element inside a 'P' element. This might at time lead to some
1756 surprising results in your output.
1757  
1758 =head1 AUTHOR
1759
1760 John Napiorkowski L<email:jjnapiork@cpan.org>
1761
1762 =head1 SEE ALSO
1763
1764 L<DOM::Tiny>, L<HTML::Zoom>. Both of these are approaches to programmatically examining and
1765 altering a DOM.
1766  
1767 L<Template::Semantic> is a similar system that uses XPATH instead of a CSS inspired matching
1768 specification. It has more dependencies (including L<XML::LibXML> and doesn't separate the actual
1769 template data from the directives. You might find this more simple approach appealing,
1770 so its worth a look.
1771
1772 =head1 COPYRIGHT & LICENSE
1773
1774 Copyright 2016, John Napiorkowski L<email:jjnapiork@cpan.org>
1775
1776 This library is free software; you can redistribute it and/or modify it under
1777 the same terms as Perl itself.
1778  
1779 =cut
« Pure/DataContext.pm ↑ Summary Pure/DataProxy.pm »