Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure Dancer2 and Template Toolkit to use a different Stash module

How would I modify the default configuration of Template Toolkit in a Dancer2 site to make use of Template::Stash::AutoEscaping?

like image 511
Cebjyre Avatar asked Oct 09 '17 10:10

Cebjyre


1 Answers

You can obviously not write Perl code that creates a new object in your configuration file. Instead, I would subclass the Dancer2::Template::TemplateToolkit class, make the modifications there and then use that instead.

If you look at the code or D2::T::TT you can see that it creates and returns the $tt object in the method _build_engine. If you wrap this in an around in your subclass, you can grab it and make the changes.

package Dancer2::Template::TemplateToolkit::AutoEscaping;

use Moo;
use Template::Stash::AutoEscaping;

extends 'Dancer2::Template::TemplateToolkit';

around '_build_engine' => sub {
    my $orig = shift;
    my $self = shift;

    my $tt = $self->$orig(@_);

    # replace the stash object
    $tt->service->context->{STASH} = Template::Stash::AutoEscaping->new;

    return $tt;
};

1;

This is a bit of an ugly hack and rummaging in the internals of a class is never a good idea, but then Template::Context does not provide a way to change the stash object. The ->stash method is only a reader and it can only be set at runtime.

You can then use your new subclass in your config file instead of template_toolkit.

engines:
  template:
    TemplateToolkit::AutoEscaping:
      start_tag: '<%'
      end_tag:   '%>'

Note that this will make you loose any configuration you might have added for the STASH in your config file. You'd have to explicitly grab the config in your wrapper, filter out the STASH if there is one and pass it along to the new new. I will leave that as an exercise for the reader.

like image 96
simbabque Avatar answered Oct 07 '22 01:10

simbabque