2 package IkiWiki::Plugin::edittemplate;
11 hook(type => "getsetup", id => "edittemplate",
13 hook(type => "needsbuild", id => "edittemplate",
14 call => \&needsbuild);
15 hook(type => "preprocess", id => "edittemplate",
16 call => \&preprocess);
17 hook(type => "formbuilder", id => "edittemplate",
18 call => \&formbuilder);
21 sub getsetup () { #{{{
29 sub needsbuild (@) { #{{{
32 foreach my $page (keys %pagestate) {
33 if (exists $pagestate{$page}{edittemplate}) {
34 if (exists $pagesources{$page} &&
35 grep { $_ eq $pagesources{$page} } @$needsbuild) {
36 # remove state, it will be re-added
37 # if the preprocessor directive is still
38 # there during the rebuild
39 delete $pagestate{$page}{edittemplate};
45 sub preprocess (@) { #{{{
48 return "" if $params{page} ne $params{destpage};
50 if (! exists $params{template} || ! length($params{template})) {
51 error gettext("template not specified")
53 if (! exists $params{match} || ! length($params{match})) {
54 error gettext("match not specified")
57 $pagestate{$params{page}}{edittemplate}{$params{match}}=$params{template};
59 return sprintf(gettext("edittemplate %s registered for %s"),
60 $params{template}, $params{match});
63 sub formbuilder (@) { #{{{
65 my $form=$params{form};
67 return if $form->field("do") ne "create";
68 my $page=$form->field("page");
70 # The tricky bit here is that $page is probably just the base
71 # page name, without any subdir, but the pagespec for a template
72 # probably does include the subdir (ie, "bugs/*"). We don't know
73 # what subdir the user will pick to put the page in. So, try them
74 # all, starting with the one that was made default.
76 foreach my $field ($form->field) {
77 if ($field eq 'page') {
78 @page_locs=$field->def_value;
79 push @page_locs, $field->options;
83 foreach my $p (@page_locs) {
84 foreach my $registering_page (keys %pagestate) {
85 if (exists $pagestate{$registering_page}{edittemplate}) {
86 foreach my $pagespec (sort keys %{$pagestate{$registering_page}{edittemplate}}) {
87 if (pagespec_match($p, $pagespec, location => $registering_page)) {
88 $form->field(name => "editcontent",
89 value => filltemplate($pagestate{$registering_page}{edittemplate}{$pagespec}, $page));
98 sub filltemplate ($$) { #{{{
99 my $template_page=shift;
102 my $template_file=$pagesources{$template_page};
103 if (! defined $template_file) {
109 $template=HTML::Template->new(
111 my $text_ref = shift;
112 $$text_ref=&Encode::decode_utf8($$text_ref);
115 filename => srcfile($template_file),
116 die_on_bad_params => 0,
121 # Indicate that the earlier preprocessor directive set
122 # up a template that doesn't work.
123 return "[[!pagetemplate ".gettext("failed to process")." $@]]";
126 $template->param(name => $page);
128 return $template->output;