stefanadams / Mojolicious-Plugin-Mojolyst

0 stars 1 forks source link

helpers created in a controller aren't visible outside #1

Open guest20 opened 11 months ago

guest20 commented 11 months ago

First of all, thanks for the free software!

In mounted apps the helpers seem to leak out to the mount-ee app... I expected helpers to be visible from outside a Mojoyst controller too...

#cpanfile
requires 'Mojolicious' => 9;
requires 'Mojolicious::Plugin::Mojolyst' => '0.01';
package MyApp::Controller::WebsiteContent;
my $database = { # LoadFile
  'interesting-text' => { 
    title => "Very intersting", body => "large amount of text" }};

helper link_to_content => sub ($c, $page) {
  return $c->link_to($database->{$page}{title} => "/$page");
};

get '/*page' => sub ($c) {
  my $page = $c->stash('page');
  return $c->render(
    title => $database->{ $page }->{title},
    content => markdown( $database->{ $page }->{body} )
  );
}

1
__DATA__
@@ page-in-a-controller.html.ep
<----  a template defined here can see link_to_content
%= link_to_content 'interesting-text'
package MyApp;
use Mojo::Base 'Mojolicious', -signatures;
...
sub startup {
...
  $self->plugin('Mojolyst' => {controllers => 'MyApp::Controller'});
...
}
1
# templates/layouts/website.html.ep
<html>
<ul>
<li><%= link_to_content 'about-us' %>  <----  a layout in templates/ can not see link_to_content
<li><%= link_to_content 'contact' %>  
</ul>
<%= content %>
</html>

# templates/thing.html.ep
<----  a template in templates/ can not see link_to_content

It might be good that the helpers don't escape their controller. I ended up just moving the helper(s) out into sub startup for the app itself...

guest20 commented 11 months ago

Oh, I see, when my routes are dispatched their first argument ($c) is a generic Mojolicious::Controller and not a MyApp::Controller::WebsiteContent...

(That also means I can't has attributes in my controllers)

s1037989 commented 10 months ago

Ah great! Glad you figured it out! I'm delighted to hear that this plugin still works since it was created 6 years ago, so ~Mojolicious 7.31.

Yeah, disappointing to not be able to has, isn't it? I sometimes find myself wishing for that even when I'm writing true Mojolicious::Lite apps, in which case I realize what I'm actually wanting is a helper anyway so I shrug it off and write my helper like I should. And, when I really do think it's a has I should be using, I either create an appropriate class (like MyApp::Model) and/or by that time end up switching to a full app anyway.

guest20 commented 10 months ago

Yes, it's a lovely little bit of jank.