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