wiki:Development/Code/TemplateToolkit

Version 1 (modified by munoz, 13 years ago) ( diff )

--

Using Template::Toolkit in Quattor components

In some cases, most of the code deals with printing correctly to a file, and it could be simplified a lot by using a basic template instead of zillions of print statements.

For instance, the accounts component could do.

# WARNING: UNTESTED!!!

use Template;
use CAF::FileWriter;

my $fh = CAF::FileWriter->new("/etc/passwd", log => $self);
my $tree = $config->getElementGetTree();
# This one is needed for Template::Toolkit to work with the CAF::File*
my $tpl = Template->new();
$tpl->process(\*DATA, $tree, $fh);

__DATA__

[% FOREACH user in users.pairs %]
[% user.key %]:x:[% user,value.uid %]:[% user.value.gid %]:[% user.value.comment %]:[% user.value.homeDir %]:[% user.value.shell %]
[% END %]

The advantage in some sitiations is that the representation is completely isolated from the logic that will generate it. And it may allow for a closer correspondency with the schema, if wanted.

Sometimes one template won't be enough: there will be several files of several types to print (f.i, nagios-related configuration). We still have to see how to ship different templates.

Also, we have to be careful so that we don't replace ugly code with even uglier templates!!

Note: See TracWiki for help on using the wiki.