summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/template.pm
blob: 3e024c5f81b11db1c7791fe8ef214d06f186cb09 (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. section => "widget",
  20. },
  21. }
  22. sub preprocess (@) {
  23. my %params=@_;
  24. # This needs to run even in scan mode, in order to process
  25. # links and other metadata included via the template.
  26. my $scan=! defined wantarray;
  27. if (! exists $params{id}) {
  28. error gettext("missing id parameter")
  29. }
  30. my $template_page="templates/$params{id}";
  31. add_depends($params{page}, $template_page);
  32. my $template_file=$pagesources{$template_page};
  33. return sprintf(gettext("template %s not found"),
  34. htmllink($params{page}, $params{destpage}, "/".$template_page))
  35. unless defined $template_file;
  36. my $template;
  37. eval {
  38. $template=HTML::Template->new(
  39. filter => sub {
  40. my $text_ref = shift;
  41. $$text_ref=&Encode::decode_utf8($$text_ref);
  42. chomp $$text_ref;
  43. },
  44. filename => srcfile($template_file),
  45. die_on_bad_params => 0,
  46. no_includes => 1,
  47. blind_cache => 1,
  48. );
  49. };
  50. if ($@) {
  51. error gettext("failed to process:")." $@"
  52. }
  53. $params{basename}=IkiWiki::basename($params{page});
  54. foreach my $param (keys %params) {
  55. my $value=IkiWiki::preprocess($params{page}, $params{destpage},
  56. IkiWiki::filter($params{page}, $params{destpagea},
  57. $params{$param}), $scan);
  58. if ($template->query(name => $param)) {
  59. $template->param($param =>
  60. IkiWiki::htmlize($params{page}, $params{destpage},
  61. pagetype($pagesources{$params{page}}),
  62. $value));
  63. }
  64. if ($template->query(name => "raw_$param")) {
  65. $template->param("raw_$param" => $value);
  66. }
  67. }
  68. return IkiWiki::preprocess($params{page}, $params{destpage},
  69. IkiWiki::filter($params{page}, $params{destpage},
  70. $template->output), $scan);
  71. }
  72. 1