Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

davorg's scratchpad

by davorg (Chancellor)
on Jun 01, 2004 at 17:05 UTC ( #358248=scratchpad: print w/replies, xml ) Need Help??

Demo of passing a "dynamic variable" to a template".

#!/usr/bin/perl use strict; use warnings; use Template; my $tt = Template->new; $tt->process(\*DATA, { rand => sub { rand } }) or die $tt->error; __END__ A Random number: [% rand %]

A more complex example where the dynamic variable works on a list.

#!/usr/bin/perl use strict; use warnings; use Template; use List::Util 'shuffle'; my $tt = Template->new; my @a = (1 .. 10); $tt->process(\*DATA, { shuffle => sub { shuffle @{$_[0]} }, arr => \@a }) or die $tt->error; __END__ [% arr.join(':') %] [% shuffle(arr).join(':') %]

The last example reworked to use a custom vmethod.

#!/usr/bin/perl use strict; use warnings; use Template; use List::Util 'shuffle'; no warnings 'once'; # turn off annoying error $Template::Stash::LIST_OPS->{ shuffle } = sub { my $list = shift; return [ shuffle @$list ]; }; my $tt = Template->new; my @a = (1 .. 10); $tt->process(\*DATA, { arr => \@a }) or die $tt->error; __END__ [% arr.join(':') %] [% arr.shuffle.join(':') %]
Log In?

What's my password?
Create A New User
[marto]: yay, Depeche Mode at the Barrowlands on Sunday. The best venue in Glasgow for music, despite it's looks :) Also the smallest gig DM will have played in a long time

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (12)
As of 2017-03-24 11:28 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (301 votes). Check out past polls.