Home »
Perl
How to use template views in Perl Dancer?
In this article, we will learn how to use views or templates in Perl dancer web framework?
Submitted by Godwill Tetah, on December 11, 2020
Using a view or template is very important because it saves the time to code the same style or design or layout on every page. Views enable us to simply change or update the content of the page.
This view is simply a styled html file. Perl dancer has its default directory or location where it fetches views, but we will define our own folder where we will store our own views. This is done using;
set views => path(dirname(__FILE__), 'templates'); where templates is the name of our view folder. Create a new folder called templates.
The file extension of a view file in Perl dancer is ".tt". Let us create our view file temp.tt in the templates folder.
temp.tt
<html>
<head>
<style>
body {
background-color: lightblue;
}
</style>
</head>
<body>
<center>
<h1>Welcome <% name %></h1>
</center>
</body>
</html>
Yes of course! It the view file can take HTML, CSS and more. Notice the special tag <%name%> placed after the word welcome. This is simply like a variable with value on the server code.
Now let's create our Perl file where we will then pass a value to the name variable which will be displayed in the view. Does it explain the meaning of template I explained at the beginning?
index.pl
use Dancer;
set views => path( dirname(__FILE__), 'templates' );
get '/' => sub {
template 'temp' => { name => "Phil" };
};
dance;
Notice the way I passed a value to the variable name. Now run a see result!
Output: