summaryrefslogtreecommitdiff
path: root/LedgerSMB/Template/CSV.pm
blob: bd06e4782299b021c63aacb627b11bb1b680ee83 (plain)
  1. =head1 NAME
  2. LedgerSMB::Template::CSV Template support module for LedgerSMB
  3. =head1 METHODS
  4. =over
  5. =item get_template ($name)
  6. Returns the appropriate template filename for this format.
  7. =item preprocess ($vars)
  8. Returns $vars.
  9. =item process ($parent, $cleanvars)
  10. Processes the template for text.
  11. =item postprocess ($parent)
  12. Returns the output filename.
  13. =back
  14. =head1 Copyright (C) 2007, The LedgerSMB core team.
  15. This work contains copyrighted information from a number of sources all used
  16. with permission.
  17. It is released under the GNU General Public License Version 2 or, at your
  18. option, any later version. See COPYRIGHT file for details. For a full list
  19. including contact information of contributors, maintainers, and copyright
  20. holders, see the CONTRIBUTORS file.
  21. =cut
  22. package LedgerSMB::Template::CSV;
  23. use Error qw(:try);
  24. use Template;
  25. use LedgerSMB::Template::TTI18N;
  26. sub get_template {
  27. my $name = shift;
  28. return "${name}.csv";
  29. }
  30. sub preprocess {
  31. my $rawvars = shift;
  32. my $vars;
  33. my $type = ref $rawvars;
  34. #XXX fix escaping function
  35. return $rawvars if $type =~ /^LedgerSMB::Locale/;
  36. if ( $type eq 'ARRAY' ) {
  37. for (@{$rawvars}) {
  38. push @{$vars}, preprocess( $_ );
  39. }
  40. } elsif ( !$type ) { # Scalar
  41. $vars = $rawvars;
  42. $vars =~ s/(^ +| +$)//g;
  43. $vars =~ s/"/""/g;
  44. $vars = qq|"$vars"| if $vars !~ /^\w*$/;
  45. } else { # hashes and objects
  46. for ( keys %{$rawvars} ) {
  47. $vars->{preprocess($_)} = preprocess( $rawvars->{$_} );
  48. }
  49. }
  50. return $vars;
  51. }
  52. sub process {
  53. my $parent = shift;
  54. my $cleanvars = shift;
  55. my $template;
  56. my $output;
  57. if ($parent->{outputfile}) {
  58. $output = "$parent->{outputfile}.csv";
  59. } else {
  60. $output = \$parent->{output};
  61. }
  62. $template = Template->new({
  63. INCLUDE_PATH => $parent->{include_path},
  64. START_TAG => quotemeta('<?lsmb'),
  65. END_TAG => quotemeta('?>'),
  66. DELIMITER => ';',
  67. DEBUG => ($parent->{debug})? 'dirs': undef,
  68. DEBUG_FORMAT => '',
  69. }) || throw Error::Simple Template->error();
  70. if (not $template->process(
  71. get_template($parent->{template}),
  72. {%$cleanvars, %$LedgerSMB::Template::TTI18N::ttfuncs,
  73. 'escape' => \&preprocess},
  74. $output, binmode => ':utf8')) {
  75. throw Error::Simple $template->error();
  76. }
  77. $parent->{mimetype} = 'text/csv';
  78. }
  79. sub postprocess {
  80. my $parent = shift;
  81. $parent->{rendered} = "$parent->{outputfile}.csv" if $parent->{outputfile};
  82. return $parent->{rendered};
  83. }
  84. 1;