Eugen Konkov
Eugen Konkov

Reputation: 25282

Why Mojolicious render_maybe implicitly changes stash?

I have changed default Mojolicious application in next way:

  1. Add route /test into MyApp.pm
   # Normal route to controller
   $r->get('/')->to('example#welcome');
+  $r->get('/test')->to('example#test');
}
  1. Add action test and template into MyApp::Controller::Example.pm
+
+sub test {
+  my $self =  shift;
+
+  $self->render_maybe( 'not_existent1', foo => 1 );
+  $self->render_maybe( 'not_existent2', bar => 2 );
+  $self->render;
+}
+
+1;
+
+__DATA__
+@@ example/test.html.ep
+$foo $bar
  1. Then run:
./script/my_app get /test

The output is 1--2. This is not expected because I render template without any arguments.

I'm inclined to believe that this behavior is the bug.
If not tell me please how to prevent original stash while trying to render other templates?

Upvotes: 1

Views: 115

Answers (2)

vitas
vitas

Reputation: 628

In similar situaion I use Mojolicious::Renderer::template_path():

sub test {
  my $self =  shift;

  $self->render_maybe( 'not_existent1', foo => 1 ) if $self->app->renderer->template_path({ template => "not_existent1, format => 'html', handler => 'ep'});
  $self->render_maybe( 'not_existent2', bar => 2 ) if $self->app->renderer->template_path({ template => "not_existent2, format => 'html', handler => 'ep'});
  $self->render;
}
1;

OR better create helper:

  $app->helper(template_exists => sub { 
       shift->app->renderer->template_path({ template => shift, 
                                             format => 'html',
                                             handler => 'ep'})
  });

and then:

sub test {
  my $self =  shift;/Mojolicious::Renderer#template_path

  return $self->render( 'not_existent1', foo => 1 ) if $self->template_exists('not_existeunt1');  
  return $self->render( 'not_existent2', bar => 2 ) if $self->template_exists('not_existeunt2');
  $self->render;
}

Upvotes: 0

Eugen Konkov
Eugen Konkov

Reputation: 25282

I suggest that stash keys for render_maybe should be localized in same way as they are localized for render_to_string here

Upvotes: 0

Related Questions