NAME

Kelp::Module::Template - Template processing for Kelp applications

SYNOPSIS

First ...

# conf/config.pl
{
    modules => ['Template'],
    modules_init => {
        Template => { ... }
    }
};

Then ...

# lib/MyApp.pm
sub some_route {
    my $self = shift;
    $self->template('some_template', { bar => 'foo' });
}

DESCRIPTION

This module provides an interface for using templates in a Kelp web application. It uses Template by default, but it could be easily subclassed to use anything else.

REGISTERED METHODS

template

template($filename, \%vars)

Renders a file using the currently loaded template engine. If the file doesn't have an extension, the one specified in "ext" will be assigned to it.

ATTRIBUTES

ext

The default extension of the template files. This module sets this attribute to tt, so

$self->template( 'home' );

will look for home.tt.

engine

This attribute will be initialized by the build_engine method of this module, and it is available to all code that needs access to the template engine instance. See "SUBCLASSING" for an example.

METHODS

build_engine

build_engine(%args)

This method is responsible for creating, initializing and returning an instance of the template engine used, for example Template. Override it to use a different template engine, for example Text::Haml.

render

render($template, \%vars, @rest)

This method should return a rendered text. Override it if you're subclassing and using a different template engine.

PERKS

UTF8

Template is sometimes unable to detect the correct encoding, so to ensure proper rendering, you may want to add ENCODING to its configuration:

# conf/config.pl
{
    modules      => ['Template'],
    modules_init => {
        Template => {
            ENCODING => 'utf8'
        }
    }
};

SUBCLASSING

To use a different template engine, you can subclass this module. You will need to make sure your new class does the following (for the sake of the example we will show you how to create a Text::Haml rendering module):

  • Overrides the "ext" attribute and provides the file extension of the new template files.

    attr ext => 'haml';
  • Overrides the "build_engine" method and creates an instance of the new template engine.

    sub build_engine {
        my ( $self, %args ) = @_;
        return Text::Haml->new;
    }
  • Overrides the "render" method and renders using $self->engine.

    sub render {
        my ( $self, $template, $vars, @rest ) = @_;
    
        # Get the template engine instance
        my $haml = $self->engine;
    
        # If the $template is a reference, then render string,
        # otherwise it's a file name.
        return ref($template) eq 'SCALAR'
          ? $haml->render( $$template, %$vars )
          : $haml->render_file( $template, %$vars );
    }