How to access the current template name in Mojolicious?

I would like to access the template name in Mojolicious from the template itself for debugging purposes, just like the Template Toolkit works (see here )

The __FILE__ variable works neatly, but it refers to the current file and not to the top-level template, which means that it is useless inside the layout template.

I also tried

 <%= app->renderer->template_name %> 

but no result

Is it possible at all in Mojolicious?

+7
perl mojolicious
source share
1 answer

This can be done in two different ways:

First add the before_render hook and set the variable. It's easy to pack it all inside the plugin:

 package Mojolicious::Plugin::TemplateName; use Mojo::Base 'Mojolicious::Plugin'; sub register { my ($self, $app, $conf) = @_; $app->helper('template' => sub { return shift->stash('mojo.template') }); $app->hook(before_render => sub { my $c = shift; $c->stash('mojo.template', $_[0]->{template} ) }); } 1; 

and use it inside a template like this

 <%= template %> 

Secondly, this can be done inside the templates - by setting a variable inside the template itself:

 % stash('template', __FILE__); 

and then reusing the variable in the layout:

 <%= $template %> 

In this case, you will receive a file name with a suffix and that’s all - not just with the template.

Inspired by the answer here that templates are visualized inside out.

0
source share

All Articles