8

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?

simone
  • 3,644
  • 4
  • 18
  • 32
  • In https://groups.google.com/forum/#!topic/mojolicious/f1SLFXSGRVk sri suggests to use ``. – simbabque Dec 21 '17 at 15:59
  • 1
    @simbabque it does not work if used in a wrapper template (layout) - see the question – simone Dec 21 '17 at 16:08
  • Sri also calls doing this a code smell in the thread. It seems they haven't implemented anything that allows you to do it by now. – simbabque Dec 21 '17 at 16:09

1 Answers1

1

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.

simone
  • 3,644
  • 4
  • 18
  • 32