Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the current template name in Mojolicious?

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?

like image 494
simone Avatar asked Dec 21 '17 15:12

simone


1 Answers

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.

like image 51
simone Avatar answered Nov 09 '22 08:11

simone