2 package IkiWiki::Plugin::edittemplate;
11 hook(type => "needsbuild", id => "edittemplate",
12 call => \&needsbuild);
13 hook(type => "preprocess", id => "edittemplate",
14 call => \&preprocess);
15 hook(type => "formbuilder", id => "edittemplate",
16 call => \&formbuilder);
19 sub needsbuild (@) { #{{{
22 foreach my $page (keys %pagestate) {
23 if (exists $pagestate{$page}{edittemplate}) {
24 if (grep { $_ eq $pagesources{$page} } @$needsbuild) {
25 # remove state, it will be re-added
26 # if the preprocessor directive is still
27 # there during the rebuild
28 delete $pagestate{$page}{edittemplate};
34 sub preprocess (@) { #{{{
37 return "" if $params{page} ne $params{destpage};
39 if (! exists $params{template} || ! length($params{template})) {
40 return return "[[meta ".gettext("template not specified")."]]";
42 if (! exists $params{match} || ! length($params{match})) {
43 return return "[[meta ".gettext("match not specified")."]]";
46 $pagestate{$params{page}}{edittemplate}{$params{match}}=$params{template};
48 return sprintf(gettext("edittemplate %s registered for %s"),
49 $params{template}, $params{match});
52 sub formbuilder (@) { #{{{
54 my $form=$params{form};
56 return if $form->field("do") ne "create";
57 my $page=$form->field("page");
59 # The tricky bit here is that $page is probably just the base
60 # page name, without any subdir, but the pagespec for a template
61 # probably does include the subdir (ie, "bugs/*"). We don't know
62 # what subdir the user will pick to put the page in. So, try them
63 # all, starting with the one that was made default.
65 foreach my $field ($form->field) {
66 if ($field eq 'page') {
67 @page_locs=$field->def_value;
68 push @page_locs, $field->options;
72 foreach my $p (@page_locs) {
73 foreach my $registering_page (keys %pagestate) {
74 if (exists $pagestate{$registering_page}{edittemplate}) {
75 foreach my $pagespec (sort keys %{$pagestate{$registering_page}{edittemplate}}) {
76 if (pagespec_match($p, $pagespec, location => $registering_page)) {
77 $form->field(name => "editcontent",
78 value => filltemplate($pagestate{$registering_page}{edittemplate}{$pagespec}, $page));
87 sub filltemplate ($$) { #{{{
88 my $template_page=shift;
91 my $template_file=$pagesources{$template_page};
92 if (! defined $template_file) {
98 $template=HTML::Template->new(
100 my $text_ref = shift;
101 $$text_ref=&Encode::decode_utf8($$text_ref);
104 filename => srcfile($template_file),
105 die_on_bad_params => 0,
110 return "[[pagetemplate ".gettext("failed to process")." $@]]";
113 $template->param(name => $page);
115 return $template->output;