It didn't come to my mind, gotta check it out, thanks! | [reply] [Watch: Dir/Any] |
The Mojolicious::Lite documentation is where you should be starting as you learn to use Mojolicious. "stash" may not have been an obvious solution if one is trying to figure it out without the benefit of documentation, but it is a fundamental Mojolicious concept, well documented, and exists specifically for this purpose: Stash and Templates:
The "stash" in Mojolicious::Controller is used to pass data to templates,...
use Mojolicious::Lite;
# Route leading to an action that renders a template
get '/bar' => sub {
my $self = shift;
$self->stash(one => 23);
$self->render('baz', two => 24);
};
app->start;
__DATA__
@@ baz.html.ep
The magic numbers are <%= $one %> and <%= $two %>.
From that documentation and example we can see at least two ways to pass information into templates. The first is the explicit call to stash, and the second is passing a stash value through the render call.
From within the template, stash values become Perl variables. This is useful, unless your controller logic creates certain stash values only under certain conditions, in which case the variable may not exist within a template, and a stricture violation will result. For example:
get '/bar' => sub {
my $self = shift;
if( $cond ) {
$self->stash( one => 23 );
}
else {
$self->stash( two => 42 );
}
$self->render('baz');
}
app_start;
__DATA__
@@ baz.html.ep
<%= $one %> or <%= $two %>.
Only one of those two stash values will be populated, and only one of the two will exist as variables. The simple solution is to ensure that you never create logic that will result in this shortcoming. But sometimes that can be a cumbersome limitation. Another solution is to call stash() from within the template, rather than relying on the existence of a variable in the template. This is documented in Mojolicious::Plugin::DefaultHelpers "stash":
%= stash 'foo'
% stash foo => 'bar';
...
%= stash('name') // 'Somebody'
So here within the template we're calling "stash" to retrieve a specific stash value, or in the case of stash foo => 'bar';, to set a value. In this way we're avoiding the issue of different logic paths creating different stash elements. In the final example, "%= stash('name') // 'Somebody'", if "name" is undefined, the "Somebody" value will be used.
| [reply] [Watch: Dir/Any] [d/l] [select] |