summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/template.pm
blob: 98a13b5fa55871b4d54d7f8fe1ee9599ff16e2d9 (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;
  33. if (exists $pagesources{$template_page}) {
  34. $template_file=srcfile($pagesources{$template_page});
  35. }
  36. else {
  37. $template_file=IkiWiki::template_file("$params{id}.tmpl")
  38. }
  39. return sprintf(gettext("template %s not found"),
  40. htmllink($params{page}, $params{destpage}, "/".$template_page))
  41. unless defined $template_file;
  42. my $template;
  43. eval {
  44. $template=HTML::Template->new(
  45. filter => sub {
  46. my $text_ref = shift;
  47. $$text_ref=&Encode::decode_utf8($$text_ref);
  48. chomp $$text_ref;
  49. },
  50. filename => $template_file,
  51. die_on_bad_params => 0,
  52. no_includes => 1,
  53. blind_cache => 1,
  54. );
  55. };
  56. if ($@) {
  57. error gettext("failed to process:")." $@"
  58. }
  59. $params{basename}=IkiWiki::basename($params{page});
  60. foreach my $param (keys %params) {
  61. my $value=IkiWiki::preprocess($params{page}, $params{destpage},
  62. IkiWiki::filter($params{page}, $params{destpagea},
  63. $params{$param}), $scan);
  64. if ($template->query(name => $param)) {
  65. $template->param($param =>
  66. IkiWiki::htmlize($params{page}, $params{destpage},
  67. pagetype($pagesources{$params{page}}),
  68. $value));
  69. }
  70. if ($template->query(name => "raw_$param")) {
  71. $template->param("raw_$param" => $value);
  72. }
  73. }
  74. return IkiWiki::preprocess($params{page}, $params{destpage},
  75. IkiWiki::filter($params{page}, $params{destpage},
  76. $template->output), $scan);
  77. }
  78. 1