Did you know that you can navigate the posts by swiping left and right?
While going through the files in the MB server and trying to figure out the places I need to make changes or add things to, I started feeling my lack of knowledge on Perl is starting to become a problem. So I thought of getting familiar with the basic types of syntaxes and methods used in the server with respect to the Perl language and its templates.
The first thing that bugged me was this [% %] notation. This is the way that we can embed Perl in an HTML document. The file containing these tags acts as a template which we can then provide dynamic content from another Perl script and generate dynamic HTML code. This is how it goes.
Let this be the content of a file named template.html
[% INCLUDE header %]
This is a test to generate dynamic content <br>
<a href="[% link %]">[% name %]</a>
[% INCLUDE footer %]
Then what we will do to demonstrate this is write a Perl script on another file that would generate HTML from the above template with the parameters provided.
#!/usr/bin/perl
# templategen.pl
use warnings;
use strict;
use Template;
$| = 1;
print "Content-type: text/htmlnn";
my $file = 'template.html';
my $vars = { 'link' => 'www.abcd.com', 'name' => 'ruchiranga', };
my $template = Template->new({
INCLUDE_PATH => '/home/test/templates:/home/test/lib',
});
$template->process($file, $vars) || die $template->error();
Reviewing the above code, the lines use warnings; and use strict; tells perl to use 2 programs that catch many errors sooner than they would be caught otherwise, which makes it easier to find the root causes of the errors. The root cause might be the need for an error or validation check, and that can happen regardless or programmer skill. Having my in front of each variable declaration is because of this line use strict;. As the script says, a variable named $file is made with the template file name, an array is made with the name $vars that contain the parameters to be sent to the parsing of the template. The $template variable holds an instance of the Template program which is returned by the method call Template->new(). The INCLUDE_PATH says where to look for the template. Finally the last line parses the loaded template with the given parameters.
In addition to all the template tags mentioned above many other tags exist. One such is the following.
$vars = { 'names' => [ 'Ruchi', 'Ranga', 'Thanu', 'Wicky' ], };
where in the template can be accessed as
[% FOREACH name = names %]
Name is [% name %] <br>
[% END %]
which would simply iterate through those names in the given array and generate the specified HTML.