How to use layouts in Perl Dancer web framework?

In this tutorial, we will learn how to work with layouts in Perl dancer web framework?
Submitted by Godwill Tetah, on December 11, 2020

A layout can be described as a design which can be placed anywhere on a web page. It is recommended you have some knowledge on template views.

Think of it like banners which could be placed anywhere depending on the need. Now, it actually solves the problem of writing same code on every section or many times.

A layout is a special view which has the special tag <%content%> which acts like a representative of the main content of the web page and is used to indicate where the layout can be placed.

We are going to make use of a view temp.tt where we will pass a variable called name which we will use to welcome our user in this example. On the view template, we will then add a layout at the top.

Our view will be located in templates folder while our layout will be located in layouts folder. Ensure you create both folders.

Now let us begin with the code for our view.

temp.tt

<html>
    <head>
        <style>
            body {
                background-color: lightblue;
            }
        </style>
    </head>
    <body>
        <center>
            <h1>Welcome <% name %></h1>
        </center>
    </body>
</html>

Layout file; header.tt

<html>
    <head>
        <style></style>
    </head>
    <body>
        <div style="background-color: yellow;">
            header
        </div>
        <div id="content">
            <% content %>
        </div>
    </body>
</html>

Now let us code our main Perl script.

index.pl

use Dancer;
set views => path( dirname(__FILE__), 'templates' );
set layout => 'header';    #setting the layout to our file name

get '/' => sub {
    template 'temp' => { name => "john" };
};

dance;

Output:

layouts in Perl Dancer web framework




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.