comments
[ikiwiki.git] / IkiWiki / Plugin / template.pm
1 #!/usr/bin/perl
2 # Structured template plugin.
3 package IkiWiki::Plugin::template;
4
5 use warnings;
6 use strict;
7 use IkiWiki 3.00;
8 use HTML::Template;
9 use Encode;
10
11 sub import {
12         hook(type => "getsetup", id => "template", call => \&getsetup);
13         hook(type => "preprocess", id => "template", call => \&preprocess,
14                 scan => 1);
15 }
16
17 sub getsetup () {
18         return
19                 plugin => {
20                         safe => 1,
21                         rebuild => undef,
22                 },
23 }
24
25 sub preprocess (@) {
26         my %params=@_;
27
28         if (! exists $params{id}) {
29                 error gettext("missing id parameter")
30         }
31
32         my $template_page="templates/$params{id}";
33         add_depends($params{page}, $template_page);
34
35         my $template_file=$pagesources{$template_page};
36         return sprintf(gettext("template %s not found"),
37                 htmllink($params{page}, $params{destpage}, "/".$template_page))
38                         unless defined $template_file;
39
40         my $template;
41         eval {
42                 $template=HTML::Template->new(
43                         filter => sub {
44                                 my $text_ref = shift;
45                                 $$text_ref=&Encode::decode_utf8($$text_ref);
46                                 chomp $$text_ref;
47                         },
48                         filename => srcfile($template_file),
49                         die_on_bad_params => 0,
50                         no_includes => 1,
51                         blind_cache => 1,
52                 );
53         };
54         if ($@) {
55                 error gettext("failed to process:")." $@"
56         }
57
58         $params{basename}=IkiWiki::basename($params{page});
59
60         foreach my $param (keys %params) {
61                 if ($template->query(name => $param)) {
62                         $template->param($param =>
63                                 IkiWiki::htmlize($params{page}, $params{destpage},
64                                         pagetype($pagesources{$params{page}}),
65                                         $params{$param}));
66                 }
67                 if ($template->query(name => "raw_$param")) {
68                         $template->param("raw_$param" => $params{$param});
69                 }
70         }
71
72         return IkiWiki::preprocess($params{page}, $params{destpage},
73                 IkiWiki::filter($params{page}, $params{destpage},
74                 $template->output));
75 }
76
77 1