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

How do I change the default configuration of the Template Toolkit on Dancer2 to use Template :: Stash :: AutoEscaping ?

+5
source share
1 answer

Obviously, you cannot write Perl code that creates a new object in your configuration file. Instead, I would subclass the class Dancer2 :: Template :: TemplateToolkit by making changes there and then using it.

If you look at the code or D2 :: T :: TT , you will see that it creates and returns the $tt object in the _build_engine method. If you wrap this in around in your subclass, you can capture it and make 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 ugly hack and jerk in the internal elements of the class, this is not a good idea, but then Template :: Context does not provide a way to modify the stash object. The method ->stash is only a reader and can only be set at runtime.

Then you can use your new subclass in the configuration file instead of template_toolkit .

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

Please note that this will save you any configuration that you could add for stash in your configuration file. You will need to explicitly capture the configuration in your wrapper, filter out the stash , if any, and pass it along with the new new . I will leave this as an exercise for the reader.

+6
source

Source: https://habr.com/ru/post/1272450/


All Articles