Pure.pm

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