I'd like to access the template name in Mojolicious from inside the template itself for debugging purposes, in the same way the Template Toolkit does (see here)
The variable __FILE__
works neatly but it refers to the current file and not to the top level template, which means it's useless inside a layout template.
I've also tried
<%= app->renderer->template_name %>
but no result
Is it possible at all in Mojolicious?
This can be done in two slightly different ways:
First by adding a before_render
hook and setting a variable. It's easy to pack it all inside a plugin like so:
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 %>
Second, it can be done inside the templates - by setting the variable inside the template itself:
% stash('template', __FILE__);
and then reusing the variable in the layout:
<%= $template %>
In this case you get the file name with suffix and all - not just the template.
Inspired by the answer here about templates being rendered inside-out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With