View/ByCode.pm

filter: Statementstmt 83.5% 173 / 207 Branchbran 45.0% 27 / 60 Conditioncond 39.3% 13 / 33 MC/DCmcdc 15.0% 3 / 20 Subroutinesub 92.0% 23 / 25 Podpod 66.6% 2 / 3 totaltotal 69.2% 241 / 348 CC 43 SCAR 29.5
CC
43
Cov
71%
render
71.0
_compile_template
13.5
_find_template
10.6
CRAP 19.0
« View/ByCode/Renderer.pm ↑ Summary View/ByCode/Declare.pm »
1 package Catalyst::View::ByCode;
2 4 $Catalyst::View::ByCode::VERSION = '0.28';
3 4 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 extends 'Catalyst::View';
5 4 with 'Catalyst::Component::ApplicationAttribute';
6  
7 4 has extension => (is => 'rw', default => '.pl');
8 4 has root_dir => (is => 'rw', default => 'root/bycode');
9 4 has wrapper => (is => 'rw', default => 'wrapper.pl');
10 3 ▶has include => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
11 4 has content_type => (is => 'rw', default => 'text/html ; charset=utf-8');
12  
13 # Config Options:
14 # root_dir => 'bycode',
15 # extension => '.pl',
16 # wrapper => 'wrapper.pl', # will be overridden by stash{wrapper}
17 # include => [...] -- packages to use in every template
18 #
19 # Stash Variables:
20 # template => 'path/to/template'
21 # yield => { name => 'path/to/yield' }
22 # wrapper => 'path/to/wrapper'
23 #
24 # set by Catalyst (we need them!):
25 # - current_view
26 # - current_view_instance
27 #
28 #
29  
30 4 ▶use Catalyst::View::ByCode::Renderer qw(:markup);
Subroutine BEGIN: called CC=1 SCAR=0.0
31 4 ▶use Catalyst::Utils;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 4 ▶use UUID::Random;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 4 ▶use Path::Class::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 4 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
35  
36 4 our $compiling_package; # local() ized during a compile
37  
38 =head1 NAME
39  
40 Catalyst::View::ByCode - Templating using pure Perl code
41  
42 =head1 VERSION
43  
44 version 0.28
45  
46 =head1 SYNOPSIS
47  
48 # 1) use the helper to create your View
49 ./script/myapp_create.pl view ByCode ByCode
50  
51  
52 # 2) inside your Controllers do business as usual:
53 sub index :Path :Args(0) {
54 my ($self, $c) = @_;
55
56 # unless defined as default_view in your config, specify:
57 $c->stash->{current_view} = 'ByCode';
58
59 $c->stash->{title} = 'Hello ByCode';
60
61 # if omitted, would default to
62 # controller_namespace / action_namespace .pl
63 $c->stash->{template} = 'hello.pl';
64 }
65  
66  
67 # 3) create a simple template eg 'root/bycode/hello.pl'
68 # REMARK:
69 # use 'c' instead of '$c'
70 # prefer 'stash->{...}' to 'c->stash->{...}'
71 template {
72 html {
73 head {
74 title { stash->{title} };
75 load Js => 'site.js';
76 load Css => 'site.css';
77 };
78 body {
79 div header.noprint {
80 ul.topnav {
81 li { 'home' };
82 li { 'surprise' };
83 };
84 };
85 div content {
86 h1 { stash->{title} };
87 div { 'hello.pl is running!' };
88 img(src => '/static/images/catalyst_logo.png');
89 };
90 };
91 };
92 };
93 # 274 characters without white space
94
95
96 # 4) expect to get this HTML generated:
97 <html>
98 <head>
99 <title>Hello ByCode!</title>
100 <script src="http://localhost:3000/js/site.js"
101 type="text/javascript">
102 </script>
103 <link rel="stylesheet"
104 href="http://localhost:3000/css/site.css"
105 type="text/css" />
106 </head>
107 <body>
108 <div id="header" style="noprint">
109 <ul class="topnav">
110 <li>home</li>
111 <li>surprise</li>
112 </ul>
113 </div>
114 <div class="content">
115 <h1>Hello ByCode!</h1>
116 <div>hello.pl is running!</div>
117 <img src="/static/images/catalyst_logo.png" />
118 </div>
119 </body>
120 </html>
121 # 453 characters without white space
122  
123 =head1 DESCRIPTION
124  
125 C<Catalyst::View::ByCode> tries to offer an efficient, fast and robust
126 solution for generating HTML and XHTML markup using standard perl code
127 encapsulating all nesting into code blocks.
128  
129 Instead of typing opening and closing HTML-Tags we simply call a
130 sub named like the tag we want to generate:
131  
132 div { 'hello' }
133
134 generates:
135  
136 <div>hello</div>
137  
138 There is no templating language you will have to learn, no quirks with
139 different syntax rules your editor might not correctly follow and no
140 indentation problems.
141  
142 The whole markup is initially constructed as a huge tree-like
143 structure in memory keeping every reference as long as possible to
144 allow greatest flexibility and enable deferred construction of every
145 building block until the markup is actially requested.
146  
147 Every part of the markup can use almost every type of data with some
148 reasonable behavior during markup generation.
149  
150 =head2 Tags
151  
152 Every tag known in HTML (or defined in L<HTML::Tagset> to be precise) gets
153 exported to a template's namespace during its compilation and can be used as
154 expected. However, there are some exceptions which would collide with CORE
155 subs or operators
156  
157 =over 12
158  
159 =item choice
160  
161 generates a E<lt>selectE<gt> tag
162  
163 =item link_tag
164  
165 generates a E<lt>linkE<gt> tag
166  
167 =item trow
168  
169 generates a E<lt>trE<gt> tag
170  
171 =item tcol
172  
173 generates a E<lt>tdE<gt> tag
174  
175 =item subscript
176  
177 generates a E<lt>subE<gt> tag
178  
179 =item superscript
180  
181 generates a E<lt>supE<gt> tag
182  
183 =item meta_tag
184  
185 generates a E<lt>metaE<gt> tag
186  
187 =item quote
188  
189 generates a E<lt>qE<gt> tag
190  
191 =item strike
192  
193 generates a E<lt>sE<gt> tag
194  
195 =item map_tag
196  
197 generates a E<lt>mapE<gt> tag
198  
199 =back
200  
201 Internally, every tag subroutine is defined with a prototype like
202  
203 sub div(;&@) { ... }
204  
205 Thus, the first argument of this sub is expected to be a coderef, which allows
206 to write code like the examples above. Nesting tags is just a matter of
207 nesting calls into blocks.
208  
209 =head2 Content
210  
211 There are several ways to generate content which is inserted between the
212 opening and the closing tag:
213  
214 =over
215  
216 =item
217  
218 The return value of the last expression of a code block will get appended to
219 the content inside the tag. The content will get escaped when needed.
220  
221 =item
222  
223 To append any content (getting escaped) at any point of the markup generation,
224 the C<OUT> glob can be used:
225  
226 print OUT 'some content here.';
227  
228 =item
229  
230 To append unescaped content eg JavaScript or the content of another
231 markup-generating subsystem like C<HTML::FormFu> simple use the <RAW> glob:
232  
233 print RAW '<?xxx must be here for internal reasons ?>';
234  
235 =back
236  
237 =head2 Attributes
238  
239 As usual for Perl, there is always more than one way to do it:
240  
241 =over
242  
243 =item old-school perl
244  
245 # appending attributes after tag
246 div { ... content ... } id => 'top',
247 class => 'noprint silver',
248 style => 'display: none';
249  
250 the content goes into the curly-braced code block immediately following the
251 tag. Every extra argument after the code block is converted into the tag's
252 attributes.
253  
254 =item special content
255  
256 # using special methods
257 div {
258 id 'top';
259 class 'noprint silver';
260 attr style => 'display: none';
261
262 'content'
263 };
264  
265 Every attribute may be added to the latest opened tag using the C<attr> sub. However, there are some shortcuts:
266  
267 =over 8
268  
269 =item id 'name'
270  
271 is equivalent to C<<< attr id => 'name' >>>
272  
273 =item class 'class'
274  
275 is the same as C<<< attr class => 'class' >>>
276  
277 However, the C<class> method is special. It allows to specify a
278 space-separated string, a list of names or a combination of both. Class names
279 prefixed with C<-> or C<+> are treated special. After a minus prefixed class
280 name every following name is subtracted from the previous list of class names.
281 After a plus prefixed name all following names are added to the class list. A
282 list of class names without a plus/minus prefix will start with an empty class
283 list and then append all subsequentially following names.
284  
285 # will yield 'abc def ghi'
286 div.foo { class 'abc def ghi' };
287
288 # will yield 'foo def xyz'
289 div.foo { class '+def xyz' };
290
291 # will yield 'bar'
292 div.foo { class '-foo +bar' };
293  
294 =item on handler => 'some javascript code'
295  
296 produces the same result as C<attr onhandler => 'some javascript code'>
297  
298 div {
299 on click => q{alert('you clicked me')};
300 };
301  
302 =back
303  
304 =item tricky arguments
305  
306 div top.noprint.silver(style => 'display: none') {'content'};
307  
308 =item even more tricky arguments
309  
310 div top.noprint.silver(style => {display => 'none'}) {'content'};
311  
312 =item tricky arguments and CamelCase
313  
314 div top.noprint.silver(style => {marginTop => '20px'}) {'foo'};
315  
316 C<marginTop> or C<margin_top> will get converted to C<margin-top>.
317  
318 =item handling scalar refs
319  
320 div (data_something => \'<abcd>') { ... };
321  
322 will not escape the ref-text <abcd>.
323  
324 =item code refs
325  
326 div (id => \&get_next_id) { ... };
327  
328 will call get_next_id() and set its return value as a value for id and in case
329 of special characters, escapes it.
330  
331 =back
332  
333 Every attribute may have almost any datatype you might think of:
334  
335 =over
336  
337 =item scalar
338  
339 Scalar values are taken verbatim.
340  
341 =item hashref
342  
343 Hash references are converted to semicolon-delimited pairs of the key, a colon
344 and a value. The perfect solution for building inline CSS. Well, I know,
345 nobody should do something, but sometimes...
346  
347 Keys consisting of underscore characters and CAPITAL letters are converted to
348 dash-separated names. C<dataTarget> or C<data_target> both become C<data-target>.
349  
350 =item arrayref
351  
352 Array references are converted to space separated things.
353  
354 =item coderef -- FIXME: do we like this?
355  
356 no idea if we like this
357  
358 =item other refs
359  
360 all other references simply are stringified. This allows the various objects
361 to forward stringification to their class-defined code.
362  
363 =back
364  
365  
366 =head2 Exported subs
367  
368 =over
369  
370 =item attr
371  
372 Setter or Getter for attribute values. Using the C<attr> sub refers to the
373 latest open tag and sets or gets its attribute(s):
374  
375 div {
376 attr(style => 'foo:bar'); # set 'style' attribute
377 attr('id'); # get 'id' attribute (or undef)
378
379 ... more things ...
380 a {
381 attr(href => 'http://foo.bar'); # refers to 'a' tag
382 };
383
384 attr(lang => 'de'); # sets attribute in 'div' tag
385 };
386  
387 =item block
388  
389 define a block that may be used like a tag. If a block is defined in a
390 package, it is automatically added to the package's C<@EXPORT> array.
391  
392 # define a block
393 block navitem {
394 my $id = attr('id');
395 my $href = attr('href');
396 li {
397 id $id if ($id);
398 a(href => $href || 'http://foo.bar') {
399 block_content;
400 };
401 };
402 };
403
404 # use the block like a tag
405 navitem some_id (href => 'http://bar.baz') {
406 # this gets rendered by block_content() -- see above
407 'some text or other content';
408 }
409
410 # will generate:
411 <li id="some_id">
412 <a href="http://bar.baz">some text or other content</a>
413 </li>
414  
415 =item block_content
416  
417 a simple shortcut to render the content of the block at a given point. See
418 example above.
419  
420 =item c
421  
422 holds the content of the C<$c> variable. Simple write C<<< c->some_method >>>
423 instead of C<<< $c->some_method >>>.
424  
425 =item class
426  
427 provides a shortcut for defining class names. All examples below will generate
428 the same markup:
429  
430 div { class 'class_name'; };
431 div { attr class => 'class_name'; };
432 div { attr('class', 'class_name'); };
433 div.class_name {};
434  
435 Using the C<class()> subroutine allows to prefix a class name with a C<+> or
436 C<-> sign. Every class name written after a C<+> sign will get appended to the
437 class, each name written after a C<-> sign will be erased from the class.
438  
439 =item doctype
440  
441 a very simple way to generate a DOCTYPE declatation. Without any arguments, a
442 HTML 5 doctype declaration will be generated. The arguments (if any) will
443 consist of either of the words C<html> or C<xhtml> optionally followed by one
444 or more version digits. The doctypes used are taken from
445 L<http://hsivonen.iki.fi/doctype/>.
446  
447 some examples:
448  
449 doctype; # HTML 5
450 doctype 'html'; # HTML 5
451 doctype html => 4; # HTML 4.01
452 doctype 'html 4'; # HTML 4.01
453 doctype 'html 4s'; # HTML 4.01 strict
454 doctype 'html 4strict'; # HTML 4.01 strict
455  
456 doctype 'xhtml'; # XHTML 1.0
457 doctype 'xhtml 1 1'; # XHTML 1.1
458  
459 =item id
460  
461 provides a shortcut for defining id names. All examples here will generate the
462 same markup:
463  
464 div { id 'id_name'; };
465 div { attr id => 'id_name'; };
466 div { attr('id', 'id_name'); };
467 div id_name {};
468  
469 =item load
470  
471 an easy way to include assets into a page. Assets currently are JavaScript or
472 CSS. The first argument to this sub specifies the kind of asset, the second
473 argument is the URI to load the asset from.
474  
475 Some examples will clearify:
476  
477 load js => '/static/js/jquery.js';
478 load css => '/static/css/site.css';
479  
480 If you plan to develop your JavaScript or CSS files as multiple files and like
481 to combine them at request-time (with caching of course...), you might like to
482 use L<Catalyst::Controller::Combine>. If your controllers are named C<Js> and
483 C<Css>, this will work as well:
484  
485 load Js => 'name_of_combined.js';
486  
487 =item on
488  
489 provides a syntactic sugar for generating inline JavaScript handlers.
490  
491 a(href => '#') {
492 on click => q{alert('you clicked me'); return false};
493 };
494  
495 =item params
496  
497 generates a series of C<param> tags.
498  
499 applet ( ... ) {
500 params(
501 quality => 'foo',
502 speed => 'slow',
503 );
504 };
505  
506 =item stash
507  
508 is a shortcut for C<<< c->stash >>>.
509  
510 =item template
511  
512 essentially generates a sub named C<RUN> as the main starting point of every
513 template file. Both constructs will be identical:
514  
515 sub RUN {
516 div { ... };
517 }
518
519 template {
520 div { ... };
521 };
522  
523 Be careful to add a semicolon after the C<template> definition if you add code
524 after it!!!
525  
526 =item yield
527  
528 Without arguments, C<yield> forwards exection to the next template in the
529 ordinary execution chain. Typically this is the point in a wrapper template
530 that includes the main template.
531  
532 With an argument, it forwards execution to the template given as the argument.
533 These values are possible:
534  
535 =over
536  
537 =item just a symbolic name
538  
539 if a symbolic name is given, this name is searched in the C<<< stash->{yield}->{...} >>>
540 hashref. If it is found, the file-name or subref stored there will be executed
541 and included at the given point.
542  
543 =item a path name
544  
545 if a template file exists at the path name given as the argument, this
546 template is compiled and executed.
547  
548 =item a code-ref
549  
550 a code ref is directly executed.
551  
552 =back
553  
554 If yield is not able to find something, simply nothing happens. This behavior
555 could be useful to add hooks at specified positions in your markup that may
556 get filled when needed.
557  
558  
559 =back
560  
561 =head2 Building Reusable blocks
562  
563 You might build a reusable block line the following calls:
564  
565 block 'block_name', sub { ... };
566
567 # or:
568 block block_name => sub { ... };
569
570 # or shorter:
571 block block_name { ... };
572  
573 The block might get used like a tag:
574  
575 block_name { ... some content ... };
576  
577 If a block-call contains a content it can get rendered inside the block using
578 the special sub C<block_content>. A simple example makes this clearer:
579  
580 # define a block:
581 block infobox {
582 # attr() values must be read before generating markup
583 my $headline = attr('headline') || 'untitled';
584 my $id = attr('id');
585 my $class = attr('class');
586
587 # generate some content
588 div.infobox {
589 id $id if ($id);
590 class $class if ($class);
591
592 div.head { $headline };
593 div.info { block_content };
594 };
595 };
596
597 # later we use the block:
598 infobox some_id.someclass(headline => 'Our Info') {
599 'just my 2 cents'
600 };
601
602 # this HTML will get generated:
603 <div class="someclass" id="some_id">
604 <div class="head">Our Info</div>
605 <div class="info">just my 2 cents</div>
606 </div>
607  
608 every block defined in a package is auto-added to the packages C<@EXPORT>
609 array and mangled in a special way to make the magic calling syntax work after
610 importing it into another package.
611  
612 =head1 CONFIGURATION
613  
614 A simple configuration of a derived Controller could look like this:
615  
616 __PACKAGE__->config(
617 # Change extension (default: .pl)
618 extension => '.pl',
619
620 # Set the location for .pl files (default: root/bycode)
621 root_dir => cat_app->path_to( 'root', 'bycode' ),
622
623 # This is your wrapper template located in root_dir
624 # (default: wrapper.pl)
625 wrapper => 'wrapper.pl',
626
627 # all these modules are use()'d automatically
628 include => [Some::Module Another::Package],
629 );
630  
631 By default a typical standard configuration setting is constructed by issuing
632 the Helper-Module. It looks like this and describes all default settings:
633  
634 __PACKAGE__->config(
635 # # Change default
636 # extension => '.pl',
637 #
638 # # Set the location for .pl files
639 # root_dir => 'root/bycode',
640 #
641 # # This is your wrapper template located in the 'root_dir'
642 # wrapper => 'wrapper.pl',
643 #
644 # # specify packages to use in every template
645 # include => [ qw(My::Package::Name Other::Package::Name) ]
646 );
647  
648 The following configuration options are available:
649  
650 =over
651  
652 =item root_dir
653  
654 With this option you may define a location that is the base of all template
655 files. By default, the directory F<root/bycode> inside your application will
656 be used.
657  
658 =item extension
659  
660 This is the default file extension for template files. As an example, if your
661 Controller class is named C<MyController> and your action method calls
662 C<MyAction> then by default a template located at
663 F<root_dir/mycontroller/myaction.pl> will get used to render your markup. The
664 path and file name will get determined by concatenating the
665 controller-namespace, the action namespace and the extension configuration
666 directive.
667  
668 If you like to employ another template, you may specifiy a different path
669 using the stash variable C<template>. See L<STASH VARIABLES> below.
670  
671 =item wrapper
672  
673 A wrapper is a template that is rendered before your main template and
674 includes your main template at a given point. It "wraps" something around your
675 template. This might be useful if you like to avoid repeating the standard
676 page-setup code for every single page you like to generate.
677  
678 The default wrapper is named F<wrapper.pl> and is found directoy inside root_dir.
679  
680 See L<TRICKS/Using a wrapper> below.
681  
682 =item include
683  
684 As every template is a perl module, you might like to add other modules using
685 Perl's C<use> directive. Well, you may do that at any point inside your
686 template. However, if you repeatedly need the same modules, you could simply
687 add them as a hashref using this configuration option.
688  
689 =back
690  
691 =head1 STASH VARIABLES
692  
693 The following stash variables are used by C<Catalyst::View::ByCode>:
694  
695 =over
696  
697 =item template
698  
699 If you like to override the default behavior, you can directly specify the
700 template containing your rendering. Simply enter a relative path inside the
701 root directory into this stash variable.
702  
703 If the template stash variable is left empty, the template used to render your
704 markup will be determined by concatenating the action's namespace and the
705 extension.
706  
707 =item wrapper
708  
709 Overriding the default wrapper is the job of this stash variable. Simply
710 specify a relative path to a wrapping template into this stash variable.
711  
712 =item yield
713  
714 Yielding is a powerful mechanism. The C<yield> stash variable contains a
715 hashref that contains a template or an array-ref of templates for certain
716 keys. Every template might be a path name leading to a template or a code-ref
717 able that should be executed as the rendering code.
718  
719 C<<< $c->stash->{yield}->{content} >>> is an entry that is present by default. It
720 contains in execution order the wrapper and the template to get executed.
721  
722 Other keys may be defined and populated in a similar way in order to provide
723 hooks to magic parts of your markup generation.
724  
725 See L<TRICKS/Setting hooks at various places> below.
726  
727 =back
728  
729 =head1 TRICKS
730  
731 =head2 Using a wrapper
732  
733 If you construct a website that has lots of pages using the same layout, a
734 wrapper will be your friend. Using the default settings, a simple file
735 F<wrapper.pl> sitting in the root directory of your templates will do the job.
736 As two alternatives you could set the C<<< $c->stash->{wrapper} >>> variable to
737 another path name or specify a wrapper path as a config setting.
738  
739 # wrapper.pl
740 html {
741 head {
742 # whatever you need
743 };
744 body {
745 # maybe heading, etc.
746
747 # include your template here
748 yield;
749 };
750 };
751  
752 =head2 Setting hooks at various places
753  
754 If you need to sometimes add things at different places, simply mark these positions like:
755  
756 # in your wrapper:
757 html {
758 head {
759 # whatever you need
760
761 # a hook for extra headings
762 yield 'head_extras';
763 };
764 body {
765 # a hook for something at the very beginning
766 yield 'begin';
767
768 # maybe heading, etc.
769
770 # a hook for something after your navigation block
771 yield 'after_navigation';
772
773 # include your template here
774 yield;
775
776 # a hook for something after your content
777 yield 'end';
778 };
779 };
780
781 # in an action of your controller:
782 $c->stash->{yield}->{after_navigation} = 'path/to/foo.pl';
783  
784 In the example above, some hooks are defined. In a controller, for the hook
785 C<after_navigation>, a path to a template is filled. This template will get
786 executed at the specified position and its content added before continuing
787 with the wrapper template. If a hook's name is not a part of the
788 C<<< stash->{yield} >>> hashref, it will be ignored. However, an I<info> log entry
789 will be generated.
790  
791 =head2 Avoiding repetitions
792  
793 Every template is a perl module. It resides in its own package and every thing
794 you are not used to type is mangled into your source code before compilation.
795 It is up to you to C<use> every other module you like. A simple module could
796 look like this:
797  
798 package MyMagicPackage;
799 use strict;
800 use warnings;
801 use base qw(Exporter);
802
803 use Catalyst::View::ByCode::Renderer ':default';
804
805 our @EXPORT = qw(my_sub);
806
807 sub my_sub {
808 # do something...
809 }
810
811 block my_block {
812 # do something else
813 };
814
815 1;
816  
817 Using the Renderer class above gives your module everything a template has.
818 You can use every Tag-sub you want.
819  
820 To use this module in every template you write within an application you
821 simply populate the config of your View:
822  
823 __PACKAGE__->config(
824 include => [ qw(MyMagicPackage) ]
825 );
826  
827 =head2 Including FormFu or FormHandler
828  
829 If you are using one of the above packages to render forms, generating the
830 markup is done by the libraries. There are a couple of ways to get the
831 generated markup into our code:
832  
833 # assume stash->{form} contains a form object
834 # all of these ways will work:
835
836 # let the form object render itself
837 print RAW stash->{form}->render();
838
839 # use the form object's stringification
840 print RAW "${\stash->{form}}";
841
842 # inside any tag, let me auto-stringify
843 div { stash->{form} };
844  
845 =head2 Create your own error page
846  
847 =head2 Using ByCode markup for other things.
848  
849 Very simple:
850  
851 # in an action of your controller:
852 my $html = $c->forward('View::ByCode', render => [qw(list of files)]);
853  
854 =head2 Shortcuts
855  
856 Some attributes behave in a way that looks intuitive but also generates
857 correct markup. The examples below do not need futher explanation.
858  
859 # both things generate the same markup:
860 input(disabled => 1);
861 input(disabled => 'disabled');
862
863 input(checked => 1);
864 input(checked => 'checked');
865  
866 input(required => 1);
867 input(required => 'required');
868  
869 option(selected => 1);
870 option(selected => 'selected');
871  
872 textarea(readonly => 1);
873 textarea(readonly => 'readonly');
874
875 # remember that choice() generates a E<lt>selectE<gt> tag...
876 choice(multiple => 1);
877 choice(multiple => 'multiple');
878  
879 beside these examples all currently defined HTML-5 boolean attributes are
880 available: disabled, checked, hidden, inert, multiple, readonly, selected,
881 required.
882  
883 =head1 METHODS
884  
885 =cut
886  
887 4 ▶sub BUILD {
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
888 4 my $self = shift;
889
890 # no need to do that -- C::Component does it for us!!!
891 # #my $c = $self->_app;
892 # if (exists($self->config->{extension})) {
893 # $self->extension($self->config->{extension});
894 # }
895 # if (exists($self->config->{root_dir})) {
896 # $self->root_dir($self->config->{root_dir});
897 # }
898 # #$c->log->warn("directory '" . $self->root_dir . "' not present.")
899 # # if (!-d $c->path_to('root', $self->root_dir));
900 # if (exists($self->config->{wrapper})) {
901 # $self->wrapper($self->config->{wrapper});
902 # }
903 }
904  
905 #
906 # intercept dies and correct
907 # - file-name to template
908 # - line-number by subtracting top-added part
909 #
910 1 ▶sub _handle_die {
Subroutine _handle_die: called CC=3 SCAR=12.0
911 1 my $msg = shift;
912 1 ▶ die $msg if (ref($msg)); # exceptions will forward...
Branch: 1 branch
BranchTrueFalseTotal
if ref $msg 0 1 1
913
914 1 ▶ my $package = $compiling_package || caller();
Condition33%1/3
$Catalyst::View::ByCode::compiling_package || &CORE::GLOBAL::caller()
l!l&&r!l&&!r
100
MC/DC0%0/2
$Catalyst::View::ByCode::compiling_package || &CORE::GLOBAL::caller()
$Catalyst::View::ByCode::compiling_package &CORE::GLOBAL::caller()
Truth table33%1/3
A || B
A= $Catalyst::View::ByCode::compiling_packageB= &CORE::GLOBAL::caller()
ABresult
1X1
011
000
915 1 die _correct_message($package, $msg);
916 }
917  
918 #
919 # intercept warns and correct
920 # - file-name to template
921 # - line-number by subtracting top-added part
922 #
923 # then log then using Catalyst's logging facility
924 #
925 # will be called by a curried sub... -- see below
926 #
927 0 ▶sub _handle_warn {
Subroutine _handle_warn: not called CC=2 SCAR=17.9
928 0 my $logger = shift;
929 0 my $msg = shift;
930
931 0 ▶ my $package = $compiling_package || caller(1);
Condition0%0/3
$Catalyst::View::ByCode::compiling_package || &CORE::GLOBAL::caller(1)
l!l&&r!l&&!r
000
MC/DC0%0/2
$Catalyst::View::ByCode::compiling_package || &CORE::GLOBAL::caller(1)
$Catalyst::View::ByCode::compiling_package &CORE::GLOBAL::caller(1)
Truth table0%0/3
A || B
A= $Catalyst::View::ByCode::compiling_packageB= &CORE::GLOBAL::caller(1)
ABresult
1X1
011
000
932 0 $logger->warn(_correct_message($package, $msg));
933 }
934  
935 #
936 # common handling for warn- and error-verbosing
937 #
938 10 ▶sub _correct_message {
Subroutine _correct_message: called CC=4 SCAR=13.9
939 10 my $package = shift;
940 10 my $msg = shift;
941  
942 10 my ($start, $file, $line, $end)
943 = ($msg =~ m{\A (.+? \s at) \s (/.+?)\s+ line \s+ (\d+) \s* (.*) \z}xmsg);
944
945 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
946 10 ▶ if ($file &&
Branch: 1 branch
BranchTrueFalseTotal
if ($file and ${"${package}::_tempfile";} and $file eq ${"${package}::_tempfile";}) 9 1 10
Condition66%4/6
$file and ${"${package}::_tempfile";} and $file eq ${"${package}::_tempfile";}
!ll&&!rl&&r
109
$file and ${"${package}::_tempfile";}
!ll&&!rl&&r
109
MC/DC33%1/3
$file and ${"${package}::_tempfile";} and $file eq ${"${package}::_tempfile";}
$file ${"${package}::_tempfile";} $file eq ${"${package}::_tempfile";}
Truth table50%2/4
A and B and C
A= $fileB= ${"${package}::_tempfile";}C= $file eq ${"${package}::_tempfile";}
ABCresult
0XX0
10X0
1100
1111
947 9 ${"$package\::_tempfile"} &&
948 9 $file eq ${"$package\::_tempfile"}) {
949 #
950 # exception/warning inside a template
951 #
952 9 my $offset = ${"$package\::_offset"};
953 9 my $template = $package;
954 9 $template =~ s{\A .+ :: Template}{}xms;
955 9 $template =~ s{::}{/}xmsg;
956
957 # replace all file-names and line-numbers
958 9 $msg =~ s{at \s+ /.+? \s+ line \s+ (\d+)}{sprintf "at Template:$template line %d", $1-$offset}exmsg;
959 }
960
961 10 return $msg;
962 }
963  
964 =head2 render
965  
966 will be called by process to render things. If render is called with extra
967 arguments, they are treated as wrapper, template, etc...
968  
969 returns the template result
970  
971 =cut
972  
973 4 ▶sub render {
Subroutine render: called CC=13 SCAR=42.6
Pod documented
974 4 my $self = shift;
975 4 my $c = shift;
976 4 my @yield_list = @_;
977
978 #
979 # beautify dies by replacing our strange file names
980 # with the relative path of the wrapper or template
981 #
982 4 local $SIG{__DIE__} = \&_handle_die;
983 0 ▶ local $SIG{__WARN__} = sub { _handle_warn($c->log, @_) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
984
985 #
986 # must render - find template and wrapper
987 # unless given as arguments
988 #
989 4 ▶ if (!scalar(@_)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar @_) 4 0 4
990 my $template = $c->stash->{template}
991 4 ▶ || $c->action . $self->extension;
Condition33%1/3
$c->stash->{'template'} || $c->action . $self->extension
l!l&&r!l&&!r
040
MC/DC0%0/2
$c->stash->{'template'} || $c->action . $self->extension
$c->stash->{'template'} $c->action . $self->extension
Truth table33%1/3
A || B
A= $c->stash->{'template'}B= $c->action . $self->extension
ABresult
1X1
011
000
992 4 ▶ if (!defined $template) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $template) { } 0 4 4
993 0 $c->log->error('No template specified for rendering');
994 0 return 0;
995 } else {
996 4 my $path = $self->_find_template($c, $template);
997 4 my $sub;
998 4 ▶ if ($path && ($sub = $self->_compile_template($c, $path))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path and $sub = $self->_compile_template($c, $path)) { } 0 4 4
Condition33%1/3
$path and $sub = $self->_compile_template($c, $path)
!ll&&!rl&&r
040
MC/DC0%0/2
$path and $sub = $self->_compile_template($c, $path)
$path $sub = $self->_compile_template($c, $path)
Truth table33%1/3
A and B
A= $pathB= $sub = $self->_compile_template($c, $path)
ABresult
0X0
100
111
999 0 ▶ $c->log->debug("FOUND template '$template' -> '$path'") if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 0 0
1000 0 push @yield_list, $sub;
1001 } else {
1002 4 $c->log->error("requested template '$template' not found or not compilable");
1003 4 return 0;
1004 }
1005 }
1006
1007 my $wrapper = exists($c->stash->{wrapper})
1008 ? $c->stash->{wrapper}
1009 0 ▶ : $self->wrapper;
Branch: 1 branch
BranchTrueFalseTotal
exists $c->stash->{'wrapper'} ? : 0 0 0
1010 0 ▶ if ($wrapper) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wrapper) { } 0 0 0
1011 0 my $path = $self->_find_template($c, $wrapper, $template); ### FIXME: must chop off last part from $template
1012 0 my $sub;
1013 0 ▶ if ($path && ($sub = $self->_compile_template($c, $path))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path and $sub = $self->_compile_template($c, $path)) { } 0 0 0
Condition0%0/3
$path and $sub = $self->_compile_template($c, $path)
!ll&&!rl&&r
000
MC/DC0%0/2
$path and $sub = $self->_compile_template($c, $path)
$path $sub = $self->_compile_template($c, $path)
Truth table0%0/3
A and B
A= $pathB= $sub = $self->_compile_template($c, $path)
ABresult
0X0
100
111
1014 0 unshift @yield_list, $sub;
1015 } else {
1016 0 $c->log->error("wrapper '$wrapper' not found or not compilable");
1017 }
1018 } else {
1019 0 ▶ $c->log->info('no wrapper wanted') if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 0 0
1020 }
1021 }
1022
1023 #
1024 # run render-sequence
1025 #
1026 0 ▶ $c->stash->{yield} ||= {};
Condition0%0/2
$c->stash->{"yield"} ||= {}
l!l
00
MC/DC0%0/1
$c->stash->{"yield"} ||= {}
$c->stash->{"yield"}
Truth table0%0/2
A
A= $c->stash->{"yield"}
Aresult
11
00
1027 0 $c->stash->{yield}->{content} = \@yield_list;
1028 0 init_markup($self, $c);
1029
1030 0 Catalyst::View::ByCode::Renderer::yield();
1031
1032 0 my $content = get_markup();
1033 0 clear_markup;
1034
1035 0 return $content;
1036 }
1037  
1038 =head2 process
1039  
1040 fulfill the request (called from Catalyst)
1041  
1042 =cut
1043  
1044 4 ▶sub process {
Subroutine process: called CC=1 SCAR=0.0
Pod documented
1045 4 my $self = shift;
1046 4 my $c = shift;
1047
1048 4 $c->response->content_type($self->content_type);
1049 4 $c->response->body($self->render($c));
1050
1051 4 return 1; # indicate success
1052 }
1053  
1054 #
1055 # convert a template filename to a package name
1056 #
1057 14 ▶sub _template_to_package {
Subroutine _template_to_package: called CC=1 SCAR=0.0
1058 14 my $self = shift;
1059 14 my $c = shift;
1060 14 my $template = shift; # relative path
1061
1062 14 $template =~ s{\.\w+\z}{}xms;
1063 14 $template =~ s{/+}{::}xmsg;
1064
1065 14 my $package_prefix = Catalyst::Utils::class2appclass($self);
1066 14 my $package = "$package_prefix\::Template\::$template";
1067
1068 14 return $package;
1069 }
1070  
1071 #
1072 # helper: find a given template
1073 # returns: relative path to template (including extension)
1074 #
1075 # FIXME: is it wise to always climb up the directory? Think!
1076 #
1077 6 ▶sub _find_template {
Subroutine _find_template: called CC=8 SCAR=23.6
1078 6 my $self = shift;
1079 6 my $c = shift;
1080 6 my $template = shift; # relative path
1081 6 ▶ my $start_dir = shift || '';
Condition50%1/2
shift() || ''
l!l
06
MC/DC0%0/1
shift() || ''
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1082
1083 6 my $root_dir = $c->path_to($self->root_dir);
1084 6 my $ext = $self->extension;
1085 6 $ext =~ s{\A \.+}{}xms;
1086 6 my $count = 100; # prevent endless loops in case of logic errors
1087 6 ▶ while (--$count > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (--$count > 0) 6 0 6
1088 ### FIXME: these constructs will probably fail under Windows.
1089 6 ▶ if (-f "$root_dir/$start_dir/$template") {
Branch: 2 branches
BranchTrueFalseTotal
if (-f "$root_dir/$start_dir/$template") { } 5 1 6
elsif (-f "$root_dir/$start_dir/$template.$ext") { } 1 0 1
1090 # we found it
1091 5 ▶ return $start_dir ? "$start_dir/$template" : $template;
Branch: 1 branch
BranchTrueFalseTotal
$start_dir ? : 0 5 5
1092 } elsif (-f "$root_dir/$start_dir/$template.$ext") {
1093 # we found it after appending extension
1094 1 ▶ return $start_dir ? "$start_dir/$template.$ext" : "$template.$ext";
Branch: 1 branch
BranchTrueFalseTotal
$start_dir ? : 0 1 1
1095 }
1096 0 ▶ last if (!$start_dir);
Branch: 1 branch
BranchTrueFalseTotal
unless $start_dir 0 0 0
1097 0 $start_dir =~ s{/*[^/]*/*\z}{}xms;
1098 };
1099
1100 #
1101 # no success
1102 #
1103 0 return;
1104 }
1105  
1106 #
1107 # helper: find and compile a template
1108 #
1109 12 ▶sub _compile_template {
Subroutine _compile_template: called CC=12 SCAR=26.1
1110 12 my $self = shift;
1111 12 my $c = shift;
1112 12 my $template = shift;
1113 12 ▶ my $sub_name = shift || 'RUN';
Condition50%1/2
shift() || 'RUN'
l!l
012
MC/DC0%0/1
shift() || 'RUN'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1114
1115 12 ▶ return 42 if (!$template); # 42 is not a code-ref (!)
Branch: 1 branch
BranchTrueFalseTotal
unless $template 0 12 12
1116 12 ▶ $c->log->debug("compiling: $template") if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 12 12
1117
1118 #
1119 # convert between path and package
1120 #
1121 12 my $template_path;
1122 my $template_package;
1123 12 ▶ if ($template =~ m{::}xms) {
Branch: 1 branch
BranchTrueFalseTotal
if ($template =~ /::/msx) { } 0 12 12
1124 #
1125 # this is a package name
1126 #
1127 0 $template_package = $template;
1128 0 $template_path = $template;
1129 0 $template_path =~ s{::}{/}xmsg;
1130 } else {
1131 #
1132 # this is a path
1133 #
1134 12 $template_path = $template;
1135 12 $template_package = $template;
1136 12 $template_package =~ s{/}{::}xmsg;
1137 12 $template_package =~ s{\.\w+\z}{}xms;
1138 }
1139  
1140 #
1141 # see if we already know the package
1142 #
1143 12 my $package = $self->_template_to_package($c, $template_path);
1144  
1145 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1146 12 my $full_path = ${"$package\::_filename"};
1147 12 my $package_mtime = ${"$package\::_mtime"};
1148 12 ▶ my $file_mtime = $full_path && -f $full_path
Branch: 1 branch
BranchTrueFalseTotal
$full_path && -f $full_path ? : 3 9 12
Condition66%2/3
$full_path and -f $full_path
!ll&&!rl&&r
903
MC/DC50%1/2
$full_path and -f $full_path
$full_path -f $full_path
Truth table66%2/3
A and B
A= $full_pathB= -f $full_path
ABresult
0X0
100
111
1149 ? (stat $full_path)[9]
1150 : 0;
1151 4 ▶ use strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1152
1153 12 ▶ if (!$full_path || !$file_mtime) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $full_path && $file_mtime) { } 9 3 12
elsif ($file_mtime != $package_mtime) { } 0 3 3
Condition66%2/3
$full_path && $file_mtime
!ll&&!rl&&r
903
MC/DC50%1/2
$full_path && $file_mtime
$full_path $file_mtime
Truth table66%2/3
A && B
A= $full_pathB= $file_mtime
ABresult
0X0
100
111
1154 # we don't know the template or it has vanished somehow
1155 9 my $full_path = $c->path_to($self->root_dir, $template_path);
1156 9 ▶ if (-f $full_path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $full_path) 9 0 9
1157 # found!
1158 9 $self->__compile($c, "$full_path" => $package);
1159 }
1160 } elsif ($file_mtime != $package_mtime) {
1161 # we need a recompile
1162 0 $self->__compile($c, $full_path => $package);
1163 }
1164
1165 # important: must stringify method to avoid Log::Log4perl::Catalyst
1166 # to call it.
1167 12 my $method = $package->can($sub_name);
1168 12 ▶ $c->log->debug("can run: $method") if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 12 12
1169
1170 12 return $method;
1171 }
1172  
1173 # low level compile
1174 9 ▶sub __compile {
Subroutine __compile: called CC=7 SCAR=19.7
1175 9 my $self = shift;
1176 9 my $c = shift;
1177 9 my $path = shift;
1178 9 my $package = shift;
1179
1180 # allow meaningful warnings during compile
1181 9 local $compiling_package = $package;
1182
1183 9 ▶ $c->log->debug("compile template :: $path --> $package") if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 9 9
1184
1185 #
1186 # clear target package's namespace before we start
1187 #
1188 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1189 9 %{*{"$package\::"}} = ();
1190 4 ▶ use strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1191  
1192 #
1193 # slurp in the file
1194 #
1195 9 my $file_contents;
1196 9 ▶ if (open(my $file, '<', $path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $file, '<', $path) { } 9 0 9
1197 9 local $/ = undef;
1198 9 $file_contents = <$file>;
1199 9 close($file);
1200 } else {
1201 0 $c->log->error('Error opening template file $file');
1202 0 return; ### FIXME: throw exception is better
1203 }
1204  
1205 #
1206 # build some magic code around the template's code
1207 #
1208 ### my $include = join("\n", map {"use $_;"} @{$self->include});
1209 9 my $now = localtime(time);
1210 9 my $mtime = (stat($path))[9];
1211 9 my $code = <<PERL;
1212 # auto-generated code - do not modify
1213 # generated by Catalyst::View::ByCode at $now
1214 # original filename: $path
1215  
1216 package $package;
1217 use strict;
1218 use warnings;
1219 use utf8;
1220  
1221 # use Devel::Declare(); ### do we need D::D ?
1222 9 ${ \join("\n", map { "use $_;" } @{$self->include}) }
1223 use Catalyst::View::ByCode::Renderer qw(:default);
1224  
1225 # subs that are overloaded here would warn otherwise
1226 no warnings 'redefine';
1227 PERL
1228  
1229 # count lines created so far (@lines added to avoid warnings)
1230 9 my $header_lines = scalar(my @lines = split(/\n/, $code));
1231  
1232 9 $code .= "\n$file_contents;\n\n1;\n";
1233
1234 #
1235 # Devel::Declare does not work well with eval()'ed code...
1236 # thus, we need to save into a TEMP-file
1237 #
1238 9 my $tempfile = Path::Class::File->new(File::Spec->tmpdir,
1239 UUID::Random::generate . '.pl');
1240 9 ▶ $c->log->debug("tempfile = $tempfile") if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 9 9
1241 9 open(my $tmp, '>', $tempfile);
1242 9 print $tmp $code;
1243 9 close($tmp);
1244
1245 #
1246 # create some magic _variables
1247 #
1248 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1249 9 ${"$package\::_filename"} = $path;
1250 9 ${"$package\::_offset"} = $header_lines + 1;
1251 9 ${"$package\::_mtime"} = $mtime;
1252 9 ${"$package\::_tempfile"} = "$tempfile";
1253 4 ▶ use strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1254  
1255 #
1256 # compile that
1257 #
1258 9 my $compile_result = do $tempfile;
1259 9 unlink $tempfile;
1260 9 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 9 0 9
elsif (not $compile_result) { } 0 0 0
1261 #
1262 # error during compile
1263 #
1264 9 $c->error('compile error: ' . _correct_message($package, $@));
1265 #die "compile error ($package)";
1266 } elsif (!$compile_result) {
1267 #
1268 # compiled template did not return a true value
1269 #
1270 0 $c->error("Template $package did not return a true value");
1271 }
1272 9 ▶ $c->log->debug('compiling done') if $c->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $c->debug 0 9 9
1273
1274 #
1275 # done
1276 #
1277 9 return 1;
1278  
1279 }
1280  
1281 =head1 AUTHOR
1282  
1283 Wolfgang Kinkeldei, E<lt>wolfgang@kinkeldei.deE<gt>
1284  
1285 =head1 LICENSE
1286  
1287 This library is free software, you can redistribute it and/or modify
1288 it under the same terms as Perl itself.
1289  
1290 =cut
1291  
1292 4 1;
« View/ByCode/Renderer.pm ↑ Summary View/ByCode/Declare.pm »