How can I access the current template name in Mojolicious?
Asked Answered
N

1

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?

Napoli answered 21/12, 2017 at 15:21 Comment(3)
In groups.google.com/forum/#!topic/mojolicious/f1SLFXSGRVk sri suggests to use <%= __FILE__ %>.Expertize
@Expertize it does not work if used in a wrapper template (layout) - see the questionNapoli
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.Expertize
N
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.

Napoli answered 4/1, 2018 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.