#!/usr/bin/perl
use strict;
use warnings;
use DBI ();
use Template ();
print generate_ul($ARGV[0]) || "";
exit;
sub generate_ul {
my $root_id=shift;
my $dbh=DBI->connect('dbi:Pg:dbname=test');
my $sql = 'SELECT tt.node_level AS indent,tt.node_id AS id,tree.name'
. ' FROM traverse_tree(?) tt JOIN tree ON node_id=tree.id';
my $sth=$dbh->prepare($sql);
$sth->execute($root_id);
my @nodes;
while ( my $node = $sth->fetchrow_hashref() ) {
push @nodes, $node;
}
my $html;
my $tt = Template->new();
my $vars = { nodes => \@nodes };
$tt->process(\*DATA, $vars, $html);
return $html;
}
__END__
[% SET previous_indent = -1 -%]
[% FOR node IN nodes -%]
[%# Opening list tag -%]
[% IF node.indent > previous_indent -%]
[% END -%]
[%# Ending item tag (if previous item was on same level) -%]
[% IF node.indent == previous_indent -%]
[% END -%]
[%# Ending item tag + ending list tag (times removed levels) -%]
[% SET previous_outdent = previous_indent -%]
[% WHILE ( node.indent < previous_outdent ) -%]
[% SET previous_outdent = previous_outdent - 1 -%]
[% END -%]
[%# Ending item tag (if previous item was on level above) -%]
[% IF node.indent < previous_indent -%]
[% END -%]
[%# This is the actual node, with the content -%]
[% node.name | html %]
[%# Save previous_indent for next iteration -%]
[% previous_indent = node.indent -%]
[% END -%]
[%# End item and list tags if last item wasn't on top level -%]
[% WHILE ( previous_indent > -1 ) -%]
[% SET previous_indent = previous_indent - 1 -%]
[% END -%]