Mojolicious templates accessing stash values set by a Controller

1.2k Views Asked by At

I'm fairly new to Mojolicious. I've tried researching this in docs, StackOverflow, and online examples. I haven't found an adequate answer, yet. Hopefully someone can help me.

I have a Controller method/action that is supposed to display a User's profile and Account data. From within the method, I pull the User and Account objects from the DB, and push them into stash so they can be accessed by the template. I have used Dumper to ensure that they exist in stash pre-render time.

Controller action in MyApp::User

sub show_public_profile
{
    my $self = shift;

    return $self->render_not_found if ( ! defined $self->stash('username') );

    my $user = MyApp::User->new( username => $self->stash('username') );
    my $loaded = $user->load( speculative => 1 );

    if ( defined $user && $loaded != 0 )
    {
        my $account = $user->account;

        $self->stash( user => $user, account => $account );

        $LOGGER->debug( 'pre-template stash: '. Dumper($self->stash) );

        return $self->render;
    }
    else
    {
        return $self->render_not_found;
    }
}

Once I hit the template, however, nothing I've populated to the stash still exists.

Placeholder/test template: user/show_public_profile.html.ep

% my $user    = stash 'user';
% my $account = stash 'account';
<pre>stash = <%= dumper stash %></pre>
<pre>$user = <%= dumper $user %></pre>
<pre>$account = <%= dumper $account %></pre>
<h1>Profile for <%= $user->{'username'} %></h1>

Unfortunately, the inserted 'user' and 'account' values don't exist in the template's version of stash:

stash = {
  'action' => 'show_public_profile',
  'controller' => 'user',
  'mojo.captures' => {
    'action' => 'show_public_profile',
    'controller' => 'user',
    'username' => 'test_user'
  },
  'mojo.routed' => 1,
  'mojo.started' => [
    1384869014,
    663017
  ],
  'username' => 'test_user'
}

Any clue as to what I'm doing wrong, here? I'm using full Mojolicious, not Mojolicious::Lite, which most examples reference. And, I've tried every permutation of example code I can find. What am I missing?

Thanks!

0

There are 0 best solutions below