[advertisement]

Interested in putting your ad here?

Blog Entry

24th January 2003
Send to twitter Send to Facebook

For State Secrets, I'm thinking about breaking out the interface into templates. These can be better manipulated by end users. Since I want SS to run on Winders with as little fuss as possible, I want something that PPM will install without fuss. Template Toolkit, my first choice, is unknown to PPM. Bummer. MJD's Text::Template is not. Here's a script that morphs Text::Template into something TT-ish. Note that does not get TT syntax with this, but it's close enough. I present this hear without intelligent comment so that I can find on the web later.

The processor a command line tool

#!/usr/bin/perl --
# See if I can make Text::Template more TT2 like

use strict;
use warnings;
use Text::Template qw(fill_in_file);

use constant TEMPLATES => './templates';
use constant SOURCE    => './src';
use constant CONSTANTS => './templates/constants';

my $infile = (shift @ARGV || "");
while (! $infile || ! -e SOURCE . "/$infile") {
  print "Which file should I process? \n";
  $infile = <>;
  chomp $infile;
}

get_constants(CONSTANTS);

my $config = {
              TEMPLATE_DIR => TEMPLATES,
              SOURCE_DIR   => SOURCE,
              # template functions
              include      => \&include,
             };

my $processor = Text::Template->new(TYPE => 'FILE',
                                    SOURCE => SOURCE . "/$infile",
                                    DELIMITERS => ['[%', '%]']
                                   );

my $text = $processor->fill_in(HASH    => $config,
                               PACKAGE => "__CONSTANTS",
                              );
print $text, "\n";
#------
# subs
#------
sub get_constants {
  my ($file) = @_;

  return unless -e $file;

  package __CONSTANTS;
  do($file) or die "Can't parse $file: $@";
  package main;

  return;
}

# includes happen in the templates dir
sub include {
  my ($file, %args) = @_;

  return fill_in_file(TEMPLATES . "/$file", HASH => \%args);
}

Templates

header

<html>
<title>{ $title }</title>
<body>

footer

</body>
</html>

Constants roughly like TT's 'config'

$foo = "bar";
# This is a nutty test
%requires = (bar => 1, b =>2);

$sam = [0,3,5];

sub hairy {
  "I like beans!\n";
}

Source File <p>hello.html

[% include('header', title => 'hello') %]
Hello, [% $foo %]

Hello, [% hairy() %]
[% include('footer') %]

[Original use.perl.org post and comments.]

Blog archives

+ About this blog