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