Lace.pm untested

filter: Statementstmt 0.0% 0 / 1 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 0.0% 0 / 1 SCAR -
1 package Template::Lace;
2  
3 our $VERSION = '0.015';
4  
5 1;
6  
7 =head1 NAME
8  
9 Template::Lace - Logic-less, strongly typed, and componentized HTML templates.
10  
11 =head1 SYNOPSIS
12  
13 A Template Model:
14  
15 package MyApp::Template::User;
16  
17 use Moo;
18  
19 has [qw/age name motto/] => (is=>'ro', required=>1);
20  
21 sub template {
22 return q[
23 <html>
24 <head>
25 <title>User Info</title>
26 </head>
27 <body>
28 <dl id='user'>
29 <dt>Name</dt>
30 <dd id='name'> -NAME- </dd>
31 <dt>Age</dt>
32 <dd id='age'> -AGE- </dd>
33 <dt>Motto</dt>
34 <dd id='motto'> -MOTTO- </dd>
35 </dl>
36 </body>
37 </html>
38 ]
39 }
40  
41 sub process_dom {
42 my ($self, $dom) = @_;
43 $dom->dl('#user', +{
44 age=>$self->age,
45 name=>$self->name,
46 motto=>$self->motto});
47 }
48  
49 1;
50  
51 A Factory and Renderer
52  
53 my $factory = Template::Lace::Factory->new(
54 model_class=>'MyApp::Template::User');
55  
56 # Once the $factory is created you can reuse it to build new
57 # template renderer instances.
58  
59 my $renderer = $factory->create(
60 age=>42,
61 name=>'John',
62 motto=>'Life in the Fast Lane!');
63  
64 print $renderer->render;
65  
66 Outputs:
67  
68 <html>
69 <head>
70 <title>
71 User Info
72 </title>
73 </head>
74 <body id="body">
75 <dl id="user">
76 <dt>
77 Name
78 </dt>
79 <dd id="name">
80 John
81 </dd>
82 <dt>
83 Age
84 </dt>
85 <dd id="age">
86 42
87 </dd>
88 <dt>
89 Motto
90 </dt>
91 <dd id="motto">
92 Why Not?
93 </dd>
94 </dl>
95 </body>
96 </html>
97  
98 =head1 DISCLAIMER
99  
100 L<Template::Lace> is a toolkit for building HTML pages using logic-less and componentized
101 templates. As such this distribution is currently not aimed at standalone use but rather
102 exists as all the reusable bits that fell out when I refactored L<Catalyst::View::Template::Lace>.
103 So currently this toolkit then exists to support the L<Catalyst> View and as a result documentation
104 here is high level and API level. If you want to integrate L<Template::Lace> into other
105 web frameworks you might wish to review L<Catalyst::View::Template::Lace> for a possible
106 approach. Ideas about how to make this distribution more usefully stand alone are quite welcomed!
107 Examples given here are probably more verbose than it would be if using this under a web
108 framework like L<Catalyst> (see L<Catalyst::View::Template::Lace>).
109  
110 You may wish to review the files under the C</examples> directory of this distribution to
111 see a L<Web::Simple> proof of concept.
112  
113 B<NOTE> Since this is still under heavy development and review I reserve the right to make
114 breaking changes, or to conclude the approach is fundementally flawed and exit the project. Do
115 not use this code in production aimed systems unless you are skilled enough to take on that
116 risk and responsibility.
117  
118 =head1 DESCRIPTION
119  
120 L<Template::Lace> is a toolkit that makes it possible to bind HTML templates to plain old Perl
121 classes as long as they provide a defined interface. These
122 templates are fully HTML markup only; they contain no display logic, only valid HTML and component
123 declarations. We use L<Template::Lace::DOM> (which is a subclass of L<Mojo::DOM58>) to alter the
124 template for presentation at request time. L<Template::Lace::DOM> provides an API to transform
125 the template into HTML using instance data and methods provided by the class. See the class
126 L<Template::Lace::DOM> and L<Mojo::DOM58> for more about how these classes allow you to inspect
127 and modify a DOM.
128  
129 When you have a Perl class that conform to these requirements we call that a 'Model' class
130 Here's an example of a very simple Model class:
131  
132 package MyApp::Template::User;
133  
134 use Moo;
135  
136 has [qw/age name motto/] => (is=>'ro', required=>1);
137  
138 sub template { q[
139 <html>
140 <head>
141 <title>User Info</title>
142 </head>
143 <body>
144 <dl id='user'>
145 <dt>Name</dt>
146 <dd id='name'> -NAME- </dd>
147 <dt>Age</dt>
148 <dd id='age'> -AGE- </dd>
149 <dt>Motto</dt>
150 <dd id='motto'> -MOTTO- </dd>
151 </dl>
152 </body>
153 </html>
154 ]}
155  
156 sub process_dom {
157 my ($self, $dom) = @_;
158 $dom->dl('#user', +{
159 age=>$self->age,
160 name=>$self->name,
161 motto=>$self->motto});
162 }
163  
164 1;
165  
166 In this example the Model class defines two methods, C<process_dom> and C<template>. Any Perl class
167 can be used as Model class as long as it provides these methods (as well as a stub for C<prepare_dom>
168 which will we discuss later). The C<template> method
169 just needs to return a string. It should contain your desired HTML markup. The C<process_dom> method
170 is an instance method on your class, and it gets both C<$self> and C<$dom>, where C<$dom> is a
171 DOM representation of your template (via L<Template::Lace::DOM>). Anything you want to change about
172 the template should be done via the L<Template::Lace::DOM> API. This is a subclass of L<Mojo::DOM58>
173 a Jquery like API for transforming HTML. Our custom subclass contains some additional helper methods
174 to make common types of transforms easier. For example here we use the custom helper C<dl> to find
175 a C<dl> tag by its id and then populate its data by matching hash keys to tag ids.
176  
177 So how do you get a rendered template out of a Model class? That's the job of two additional
178 classes, L<Template::Lace::Factory> and L<Template::Lace::Renderer> (with a tag team by
179 L<Template::Lace::Components> should your template contain components; to be discussed later).
180  
181 L<Template::Lace::Factory> wraps your model class and inspects it to create an initial DOM representation
182 of the template (as well as prepare a component hierarchy, should you have components). Most
183 simply it looks like this:
184  
185 my $factory = Template::Lace::Factory->new(
186 model_class=>'MyApp::Template::User');
187  
188 Next you call the C<create> method on the C<$factory> instance with the initial arguments you want to
189 pass to the Model. Create doesn't return the Model directly, but instead returns an instance of
190 L<Template::Lace::Renderer> which is wrapping the model:
191  
192 my $renderer = $factory->create(
193 age=>42,
194 name=>'John',
195 motto=>'Life in the Fast Lane!');
196  
197 $renderer->model; # this is the actual instance of MyApp::Template::User via
198 # the provided args to ->create.
199  
200 Those initial arguments are passed to the model and used to create an instance of the model. But the
201 wrapping C<$renderer> exposes methods that are used to do the actual transformation. For example
202  
203 print $renderer->render;
204  
205 Would return:
206  
207 <html>
208 <head>
209 <title>
210 User Info
211 </title>
212 </head>
213 <body id="body">
214 <dl id="user">
215 <dt>
216 Name
217 </dt>
218 <dd id="name">
219 John
220 </dd>
221 <dt>
222 Age
223 </dt>
224 <dd id="age">
225 42
226 </dd>
227 <dt>
228 Motto
229 </dt>
230 <dd id="motto">
231 Why Not?
232 </dd>
233 </dl>
234 </body>
235 </html>
236  
237 And that is the basics of it! Once you have a C<$factory> you can call C<create> on it as many times
238 as you like to make different versions of the rendered page.
239  
240 =head1 PREPARING THE DOM
241  
242 Sometimes a Model may wish to make some modifications to its DOM once at setup time. For
243 example you might add some debugging information to the header. Although you can do this
244 in C<process_dom> it might seem wasteful if the change isn't dynamic, or bound to something
245 that can change for each request. In this case your Model may add a class method C<prepare_dom>
246 which gets access to the DOM of the template during its initial setup. Any changes you make
247 at this point will become cloned for all subsequent requests. For example:
248  
249 package MyApp::Template::List;
250  
251 use Moo;
252 with 'Template::Lace::Model::AutoTemplate';
253  
254 has [qw/form items copywrite/] => (is=>'ro', required=>1);
255  
256 sub time { return scalar localtime }
257  
258 sub prepare_dom {
259 my ($class, $dom, $merged_args) = @_;
260  
261 # Add some meta-data
262 $dom->at('head')
263 ->prepend_content("<meta startup='${\$self->time}'>");
264 }
265  
266 sub process_dom {
267 my ($self, $dom) = @_;
268 $dom->ol('#todos', $self->items);
269 }
270  
271 In this case we'd add a startup timestamp to the header area of the template, which might be
272 useful for debugging for example.
273  
274 This example also used the role L<Template::Lace::Model::AutoTemplate> which allows you to
275 pull your template from a standalone file using a simple naming convention. When your
276 templates are larger and more complex, or when you have HTML designer that prefers standalone
277 templates instead of ones mixed into Perl code, you can use this role to achieve that. See
278 the docs in L<Template::Lace::Model::AutoTemplate> for more.
279  
280 =head1 ADVANCED TEMPLATE MANIPULATION
281  
282 So far we've seen how to use C<process_dom> (and the related C<prepare_dom>) to transform your
283 template. Strickly speaking however you do not actually need to declare these methods in your
284 view model. You may instead choose to allow the renderer to 'call into' the model. This approach
285 can give the end user a bit more control over how the template is actually rendered. Example:
286  
287 package Local::Template::NoProcessDom;
288  
289 use Moo;
290  
291 sub template { qq{
292 <section>
293 Hello <span id="name">NAME</span>, you are <span id="age"></span> years old!
294 </section>
295 }}
296  
297 sub fill_name {
298 my ($self, $dom, $name) = @_;
299 $dom->do('#name', $name);
300 }
301  
302 sub fill_age {
303 my ($self, $dom, $age) = @_;
304 $dom->do('#age', $age);
305 }
306  
307 my $factory = Template::Lace::Factory->new(
308 model_class=>'Local::Template::NoProcessDom');
309  
310 my $renderer = $factory->create();
311  
312 $renderer->call('fill_name', 'John');
313 $renderer->call('fill_age', '42');
314
315 my $html = $renderer->render;
316 print $html;
317  
318 Returns:
319  
320 <section>
321 Hello <span id="name">John</span>, you are <span id="age">42</span> years old!
322 </section>
323  
324 You might find this approach useful when you have a template where you process it differently
325 depending on logic under the control of the code that gets the renderer. For example you might
326 have a form that may or may not have errors.
327  
328 B<NOTE> You can combine both approachs, have a C<process_dom> and yet also call into the view
329 model to handle special display conditions.
330  
331 =head1 COMPONENTS
332  
333 Most template systems have a mechanism to make it possible to divide your template into
334 discrete, re-usable chunks. L<Template::Lace> provides this via Components. Components are
335 custom tags embedded into your template, usually with some markup which allows you to control
336 the passing of information into the component from the Model class. In your template you
337 would declare a component like this:
338  
339 <prefix-name
340 attr1='literal value'
341 attr2='$.foo'
342 attr3=\'title:content'>
343 [some additional content such as HTML markup and text]
344 </prefix-name>
345  
346 A component doesn't have to contain anything (like the <br/> or <hr/> tag) in which case
347 its just:
348  
349 <prefix-name
350 attr1='literal value'
351 attr2='$.foo'
352 attr3=\'title:content' />
353
354 Here's an example:
355  
356 <view-footer copydate='$.copywrite' />
357  
358 And another example:
359  
360 <lace-form
361 method="post"
362 action="$.post_url">
363 <input type='text' name='user' />
364 <input type='text' name='age' />
365 <input type='text' name='motto' />
366 <input type='submit' />
367 </lace-form>
368  
369 Canonically a component is a tag in the form of '$prefix-$name' (like <prefix-name ...>)
370 and typically will contain HTML attributes (like 'attr1="Literal"') and it may also
371 have content, as in "<lace-form><input id='content' type="submit"/></lace-form>". When you render
372 a template containing components, any HTML attributes will be converted to a real value
373 and passed to the component as initialization arguments. There are three different
374 ways your attributes will be processed:
375  
376 =over4
377  
378 =item literal values
379  
380 Example: <prefix-name attr='1984'/>
381  
382 When a value is a simple literal that value is passed as is.
383  
384 =item a path from the model instance
385  
386 Example: <prefix-name attr='$.foo'/>
387  
388 This returns the value of "$self->foo", where $self is the model instance that the factory
389 created. You can follow a data path similarly to Template Toolkit, for example:
390  
391 <prefix-name attr="$.foo.bar.baz" />
392  
393 Would be the value of "$self->foo->bar->baz" (or possibly $self->foo->{bar}{baz} since we
394 follow either a method name or the key of a hash). Currently we do not follow arrayrefs.
395  
396 You'll probably use this quite often to pass instance information to your component. If
397 the path does not exist that will return a run time error.
398  
399 =item a CSS match
400  
401 Examples: <prefix-name title=\'title:content' css=\'@link' />
402  
403 When the value of the attribute begins with a '\' that means we want to get the value of
404 a CSS match to the current DOM. In Perl when a variable starts with a '\' the means its
405 a reference; so you can think of this as a reference to a point in the current DOM.
406  
407 In general the value here is just a normal CSS match specification (see L<Mojo::DOM58> for
408 details on the match specifications supported). However we have added two minor bits to
409 how L<Mojo::DOM58> works to make some types matching easier. First, if a match specification
410 ends in ':content' that means 'match the content, not the full node'. In the example case
411 "title=\'title:content'" that would get the text value of the title tag. Second, in the case
412 where you want the match to return a collection of nodes all matching the specification, you
413 would prepend a '@' to the front of it (think in Perl @variable means an array variable). In
414 the given example "css=\'@link'" we want the attribute 'css' to be a collection of all the
415 linked stylesheets in the current DOM.
416  
417 You will use this type of value when you are making components that do complex layout
418 and overlays of the current DOM (such as when you are creating a master layout page for
419 your website).
420  
421 =back
422  
423 In addition to any attributes you pass to a component via a declaration as described above
424 all components could get some of the following automatic atttributes:
425  
426 =over 4
427  
428 =item content
429  
430 If the component has content as in the following example
431  
432 <prefix-name
433 attr1='literal value'
434 attr2='$.foo'
435 attr3=\'title:content'>
436 [some addtional content such as HTML markup and text]
437 </prefix-name>
438  
439 That content will be sent to the component under the 'content' attribute
440  
441 =item container
442  
443 If the component is a subcomponent it will receive the instance model of its
444 parent as the 'container' attribute.
445  
446 =item model
447  
448 All components get the 'model' attribute, which is the model instance that contains
449 the template in which they appear. I would use this carefully since I think that
450 you would prefer to pass information from the model to the component via attributes.
451  
452 =back
453  
454 If you need to pass complex or structured data to your arguments you may do so using
455 JSON:
456  
457 <prefix-name
458 hash={"q":"The query string"}
459 array=["1","2","3"]
460 [some addtional content such as HTML markup and text]
461 </prefix-name>
462  
463 Components can be an instance of any class that does C<create> and C<process_dom>
464 but generally you will make your components out of other L<Template::Lace> models
465 since that provides the most features and template reusability. Components are added to
466 the Factory at the time you construct it:
467  
468 my $factory = Template::Lace::Factory->new(
469 model_class=>'Local::Template::List',
470 component_handlers=>+{
471 layout => sub {
472 my ($name, $args, %attrs) = @_;
473 $name = ucfirst $name;
474 return Template::Lace::Factory->new(model_class=>"Local::Template::$name");
475 },
476 lace => {
477 form => Template::Lace::Factory->new(model_class=>'Local::Template::Form'),
478 input => Template::Lace::Factory->new(model_class=>'Local::Template::Input'),
479 },
480 },
481 );
482  
483 Components are added as a hashref of data associated with the 'component_handlers'
484 initialization argument for the class L<Template::Lace::Factory>. You can either
485 attach a component to a full 'prefix-name' pair, as in the examples for 'form' and
486 'input', or you can create a component 'generator' for an entire prefix by associating
487 the prefix with a coderef which is responsible for returning a component based on the
488 actual name.
489  
490 If your components are trivial and/or you don't want to make a full model and Factory for
491 one, you can use the L<Template::Lace::Utils> subroutine C<mk_component> to assist. This
492 creates an instance of L<Template::Lace::ComponentCallback> which is a very simple component
493 defined by a code reference. These type of components are easy to make and can run faster
494 when rendering your templates but have the downside of being defined into your Factory and
495 this reduces reuse. Example:
496  
497 use Template::Lace::Utils 'mk_component';
498 my $factory = Template::Lace::Factory->new(
499 model_class=>'Local::Template::List',
500 component_handlers=>+{
501 tags => {
502 anchor => mk_component {
503 my ($self, %attrs) = @_;
504 return "<a href='$_{href}' target='$_{target}'>$_{content}</a>";
505 }
506 },
507 },
508 );
509  
510 When using this approach to creating a component, you define a subroutine that will get C<$self>
511 and C<%attrs> (where C<%attrs> is the processed attributes from your component declaration in the
512 template) and you must return
513 either a string or an instance of L<Template::Lace::DOM>. To make things easier for creating
514 simple components we localize '$_' to C<$self> and '%_' to C<%attrs>. For the most part these
515 types of components are the same as those defined via a factory but with fewer overall features
516 (for example they can't currently support C<on_component_add>). The choice for either style
517 will depend on your need for reuse and the overall complexity of the component.
518  
519 When the factory is created, it delegates the job of walking the DOM we made from the Model's
520 template and creating a hierarchy of components actually found. All found components need to
521 match something in 'component_handlers' or they will be silently ignored (this is a feature
522 since if you are using client side web components you would want those to be passed on
523 without note). When we call C<create> on the factory we initialize the component
524 hierarchy by calling C<create> on each factory component present and then when we render
525 the template we render each component and replace the full component node with th results
526 of the rendering.
527  
528 Here's a full example of a template that is a TODO list which contains a list of
529 items 'TODO' as well as a form to add new items (with the ability to give error feedback to
530 the user if they submit bad items).
531  
532 package MyApp::Template::List
533  
534 use Moo;
535  
536 has [qw/form items copywrite/] => (is=>'ro', required=>1);
537  
538 sub template {q[
539 <view-master title=\'title:content'
540 css=\'@link'
541 meta=\'@meta'
542 body=\'body:content'>
543 <html>
544 <head>
545 <title>Things To Do</title>
546 <link href="/static/summary.css" rel="stylesheet"/>
547 <link href="/static/core.css" rel="stylesheet"/>
548 </head>
549 <body>
550 <view-form id="newtodo" fif='$.form.fif' errors='$.form.errors'>
551 <view-input id='item'
552 label="Todo"
553 name="item"
554 type="text" />
555 </view-form>
556 <ol id='todos'>
557 <li> -What To Do?- </li>
558 </ol>
559 <view-footer copydate='$.copywrite' />
560 </body>
561 </html>
562 </view-master>
563 ]}
564  
565 sub process_dom {
566 my ($self, $dom) = @_;
567 $dom->ol('#todos', $self->items);
568 }
569  
570 1;
571  
572 So this Model declares a template with four components: C<view-master>, C<view-form>, C<view-input>,
573 and C<view-footer>. It also declares a C<process_dom> method to populate the C<ol> at id 'todos'.
574 The C<process_dom> should be straight forward, the C<ol> helper is smart enough to populate the
575 list for you if you pass it an array reference. Component wise we have a hierarchy that looks like
576 this:
577  
578 view-master
579 view-form
580 view-input
581 view-footer
582  
583 And we could create a C<$factory> for this model with a setup like:
584  
585 my $factory = Template::Lace::Factory->new(
586 model_class=>'MyApp::Template::List',
587 component_handlers=>+{
588 view => {
589 master => Template::Lace::Factory->new(model_class=>'MyApp::Template::Form'),
590 form => Template::Lace::Factory->new(model_class=>'MyApp::Template::Form'),
591 input => Template::Lace::Factory->new(model_class=>'MyApp::Template::Input'),
592 footer => Template::Lace::Factory->new(model_class=>'MyApp::Template::Form'),
593 },
594 },
595 );
596  
597 B<NOTE> If you have a strong convention between your component name and the Model class
598 it would be easy to take advantage of the prefix handler code reference option to automatically
599 generate your components as needed. Example given is for ease of understanding!
600  
601 The 'view-footer' component is the most simple so lets look at that first:
602  
603 package MyApp::View::Footer;
604  
605 use Moo;
606  
607 has copydate => (is=>'ro', required=>1);
608  
609 sub process_dom {
610 my ($self, $dom) = @_;
611 $dom->at('#copy')
612 ->append_content($self->copydate);
613 }
614  
615 sub template {
616 my $class = shift;
617 return q[
618 <section id='footer'>
619 <hr/>
620 <p id='copy'>copyright </p>
621 </section>
622 ];
623 }
624  
625 1;
626  
627 When we call:
628  
629 my $renderer = $factory->create(copywrite=>2017, ...);
630
631 That creates an instance of C<MyApp::Template::List> with the attribute 'copywrite' set to '2017'.
632 During this setup, we walk the component hierarchy and when we get to the 'view-footer' component
633 we call "->create(copydate=>$renderer->model->copywrite)" on it to create an instance of that
634 component. Then when we call:
635  
636 my $html_string = $renderer->render;
637  
638 We call "->render" on that component instance and replace the component node with the new
639 string. In this case that string would look like:
640  
641 <section id='footer'>
642 <hr/>
643 <p id='copy'>copyright 2017</p>
644 </section>
645  
646 and that would replace the entire node "<view-footer copydate='$.copywrite' />".
647  
648 This 'view-footer' example is probably the closest thing to a traditional 'include' or
649 'partial' template as you might have used in other template systems. For an include this
650 simple it probably seems like a lot more work and code. However as you will see the
651 component system is significantly more powerful than this, and even with an example this
652 simple you get some powerful benefits including a strong separate between HTML markup
653 and display logic, the ability to take full advantage of the power of Perl and a strongly
654 typed interface between your component at the world. These are all things that I believe
655 make your code more maintainable and les buggy. Lets look at a more complex component,
656 the 'view-form' component:
657  
658 package MyApp::View::Form;
659  
660 use Moo;
661  
662 has [qw/id fif errors content/] => (is=>'ro', required=>0);
663  
664 sub create_child {
665 my ($self, $child_factory, %init_args) = @_;
666 my $value = $self->fif->{$init_args{name}};
667 my @errors = @{$self->errors->{$init_args{name}} ||[]};
668 my $child_component = $child_factory->create(
669 %init_args,
670 value => $value,
671 errors => \@errors);
672 return $child_component;
673 }
674  
675 sub process_dom {
676 my ($self, $dom) = @_;
677 $dom->at('form')
678 ->attr(id=>$self->id)
679 ->content($self->content);
680 }
681  
682 sub template {
683 my $class = shift;
684 return q[<form></form>];
685 }
686  
687 So I deliberately made a more complex example here so you could see one of the ways
688 that parent / child interaction can occur when there is a component hierarchy. Here
689 we are letting the parent 'view-form' component be responsible for creating its own
690 child components. We are doing this so that the 'view-form' component can give information
691 about state and any errors to any input type child components. We could also have
692 had the children reach into the 'view-form' component to get that information (since
693 each child does have access to the parent via the 'container' attribute, or we could have
694 simple pulled it directly from the Model class via an html attribute, for example:
695  
696 <view-input id='item'
697 label="Todo"
698 name="item"
699 type="text"
700 fif="$.form.fif.item"
701 errors="$.form.errors.item"/>
702  
703 This part of the system is under active development and consideration, its likely
704 we haven't worked out all the best ways this needs to work, or built in all the API
705 necessary. Discussion welcomed!
706  
707 This component also demonstrates how a component that wraps content might work, since it
708 collects that content via the 'content' attribute and inserts into into its own
709 local DOM (via ->content($self->content) using L<Template::Lace::DOM>. Lets see the
710 how the 'view-input' component works:
711  
712 package MyApp::View::Input;
713  
714 use Moo;
715  
716 has [qw/id label name type value errors/] => (is=>'ro');
717  
718 sub process_dom {
719 my ($self, $dom) = @_;
720
721 # Set Label content
722 $dom->at('label')
723 ->content($self->label)
724 ->attr(for=>$self->name);
725  
726 # Set Input attributes
727 $dom->at('input')->attr(
728 type=>$self->type,
729 value=>$self->value,
730 id=>$self->id,
731 name=>$self->name);
732  
733 # Set Errors or remove error block
734 if($self->errors) {
735 $dom->ol('.errors', $self->errors);
736 } else {
737 $dom->at("div.error")->remove;
738 }
739 }
740  
741 sub template {
742 my $class = shift;
743 return q[
744 <link href="css/main.css" />
745 <style id="min">
746 div { border: 1px }
747 </style>
748 <div class="field">
749 <label>LABEL</label>
750 <input />
751 </div>
752 <div class="ui error message">
753 <ol class='errors'>
754 <li>ERROR</li>
755 </ol>
756 </div>
757 ];
758 }
759  
760 1;
761  
762 Here I think you start to get the picture of how components can organize complex
763 display logic without making a messy template. This component easily encapsulates
764 many of the parts of an input form, including label setup, value, type, etc. It
765 also displays any form errors (for example generated by L<HTML::Formhandler> during
766 a POST) or removes the HTML markup around errors. A simple include in TT would
767 have to contain loops and conditionals, and leave you with a template that was
768 not tidy at all. Additionally it would be trivial to make a subclass of this
769 template that changes the markup, adds new features or behaviors. For example
770 you could have a subclass that added CSS markup from one of the popular CSS
771 frameworks. Or you could add javascript to make the form AJAXy. Example:
772  
773 package MyApp::Role::View::StyledInput;
774  
775 use Moo;
776  
777 around 'prepare_dom', sub {
778 my ($orig, $self, $dom, @args) = @_;
779 $dom->at('input')
780 ->attr(class=>'large-input');
781 return $self->$orig($dom, @args);
782 };
783  
784 You could that add this role to any input type component. Basically the full power
785 of Perl is available!
786  
787 Finally, lets look at the 'view-master' component, which is a type of layout component
788 to add common header / footer information to your page (a standard enough thing to do
789 when building a website:
790  
791  
792 package MyApp::View::Master;
793  
794 use Moo;
795  
796 has title => (is=>'ro', required=>1);
797 has css => (is=>'ro', required=>1);
798 has meta => (is=>'ro', required=>1);
799 has body => (is=>'ro', required=>1);
800  
801 sub on_component_add {
802 my ($self, $dom) = @_;
803 $dom->title($self->title)
804 ->head(sub { $_->append_content($self->css->join) })
805 ->head(sub { $_->prepend_content($self->meta->join) })
806 ->body(sub { $_->at('h1')->append($self->body) })
807 ->at('#header')
808 ->content($self->title);
809 }
810  
811 sub template {
812 my $class = shift;
813 return q[
814 <!DOCTYPE html>
815 <html>
816 <head>
817 <meta charset="utf-8" />
818 <meta content="width=device-width, initial-scale=1" name="viewport" />
819 <title>Page Title</title>
820 <link href="/static/base.css" rel="stylesheet" />
821 <link href="/static/index.css" rel="stylesheet"/ >
822 </head>
823 <body id="body">
824 <h1 id="header">Intro</h1>
825 </body>
826 </html>
827 ];
828 }
829  
830 1;
831  
832 This is a type of component intended to perform layout work for you. In this case we are creating a common
833 header and footer and some internal market. The values for it attributes come not from the model class
834 but from the contained DOM itself. Lets look again at the top of the component declaration:
835  
836 <view-master title=\'title:content'
837 css=\'@link'
838 meta=\'@meta'
839 body=\'body:content'>
840  
841 So four attributes, all coming from the DOM associated with the 'content' area of this component. We
842 grab the content of the title tag and the content of the HTML body tag, as well as the collection (if
843 any) of the link takes (for css style sheets) and any template specific meta tags.
844  
845 If you are looking carefully you have noticed instead of a 'process_dom' method we have a 'on_component_add' method. We could do this with 'process_dom' but that method runs for every request and since this overlay contains no dynamic request bound information its more efficient to run it once ('on_component_add' runs once at setup time; the change it makes becomes part of the base DOM which is cloned for every following request). So 'on_component_add' is like 'prepare_dom' except it allows a component to modify the DOM of the view that is calling it instead of its own.
846  
847 Here's a sample of the actual result, rendering all the components (you can peek at the repository which has all the code for these examples to see how it all works)
848  
849 <html>
850 <head>
851 <meta startup="Fri Mar 31 08:43:24 2017">
852 <meta charset="utf-8">
853 <meta content="width=device-width, initial-scale=1" name="viewport">
854 <title>
855 Things To Do
856 </title>
857 <link href="/static/base.css" rel="stylesheet" type="text/css">
858 <link href="/css/input.min.css" rel="stylesheet" type="text/css">
859 <script src="/js/input.min.js" type="text/javascript"></script>
860 </head>
861 <body id="body">
862 <h1>
863 Things To Do
864 </h1>
865 <form id="newtodo">
866 <div class="field">
867 <label for="item">Todo</label>
868 <input id="item" name="item" type="text" value="milk">
869 </div>
870 <div class="ui error message">
871 <ol class="errors">
872 <li>too short
873 </li>
874 <li>too similar it existing item
875 </li>
876 </ol>
877 </div>
878 </form>
879 <ol id="todos">
880 <li>Buy Milk
881 </li>
882 <li>Walk Dog
883 </li>
884 </ol>
885 <section id="footer">
886 <hr>
887 <p id="copy">
888 copyright 2017
889 </p>
890 </section>
891 </body>
892 </html>
893  
894 So even though we have a page with a lot happening, we can write a model class that focuses
895 just on the primary task (display the list of Todos) and let components handle the other work.
896 A complex template can be logically divided into clear chunks, each dedicated to one function
897 and each with a clearly defined, strongly typed interface. I believe this leads to well
898 organized and concise templates that are maintainable over the long term.
899  
900 You can review the documentation for each of the main classes in this distribution, and/or
901 review the test cases for more examples. Or if you want to use this for building web sites
902 immediately, see L<Catalyst::View::Template::Lace> as you quickest path.
903  
904 =head1 IMPORTANT NOTE REGARDING VALID HTML
905  
906 Please note that L<Mojo::DOM58> tends to enforce rule regarding valid HTML5. For example, you
907 cannot nest a block level element inside a 'P' element. This might at times lead to some
908 surprising results in your output.
909  
910 =head1 AUTHOR
911
912 John Napiorkowski L<email:jjnapiork@cpan.org>
913
914 =head1 SEE ALSO
915  
916 L<Template::Lace::Factory>, L<Template::Lace::Component>, L<Template::Lace::Renderer>,
917 L<Template::Lace::DOM>, L<Template::Lace::Model::AutoTemplate>,
918 and L<Template::Lace::Factory::InferInitArgsRole>
919  
920 Other classes defined in this distribution
921
922 L<Mojo::DOM58>, L<HTML::Zoom>. Both of these are approaches to programmatically examining and
923 altering a DOM.
924  
925 L<Template::Semantic> is a similar system that uses XPATH instead of a CSS inspired matching
926 specification. It has more dependencies (including L<XML::LibXML> and doesn't separate the actual
927 template data from the directives. You might find this more simple approach appealing,
928 so its worth alook.
929  
930 L<HTML::Seamstress> Seems to also be prior art along these lines but I have trouble following
931 the code and it seems not active. Might be worth looking at at least for ideas!
932  
933 L<Template::Lace> A previous work of my along the same lines but based on pure.js
934 L<http://beebole.com/pure/>.
935  
936 L<PLift>, uses L<XML::LibXML>.
937  
938 L<Catalyst::View::Template::Lace> Catalyst adaptor for this with some L<Catalyst> specific
939 enhancements.
940
941 =head1 COPYRIGHT & LICENSE
942
943 Copyright 2017, John Napiorkowski L<email:jjnapiork@cpan.org>
944
945 This library is free software; you can redistribute it and/or modify it under
946 the same terms as Perl itself.
947  
948 =cut