从 MyApp.pm 访问 Catalyst 对象 $c

发布于 2024-09-12 05:20:43 字数 323 浏览 8 评论 0原文

我在 Catalyst 应用程序中使用资产插件,并且我希望每个页面的资产中包含一些 javascript 和 css 文件。

我的第一个想法是从 MyApp/lib/MyApp.pm 调用 $c->assets->include('file.js') ,我在其中进行设置和配置,但我不知道如何获取 $ c 那里。

我的下一个想法涉及使用 WRAPPER 东西,并在默认 html 模板中放置诸如 [% c.assets.include('file.js') %] 之类的调用,但调用将对象信息转储到页面,因此调用将被丑化起来抑制输出。

解决方案或新想法受到赞赏。提前致谢。

I'm using the Assets plugin in my Catalyst app, and I would like some javascript and css files included in the assets of every page.

My first thought is call $c->assets->include('file.js') from MyApp/lib/MyApp.pm where I do setup and config, but I don't know how to get a hold of $c there.

My next idea involves using the WRAPPER stuff, and placing calls like [% c.assets.include('file.js') %] in default html template, but the calls dump the object information to the page, so the calls would have to be uglied up to suppress output.

Solutions or new ideas appreciated. Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦途 2024-09-19 05:20:44

在应用程序设置期间还没有上下文对象,因为 $c 代表当前请求。

如果您使用的是 Chained,则可以在根链操作中进行调用。如果您使用非链式操作类型(例如本地、路径等),您可以在根控制器中放置开始操作。

然而,我认为最正确的方法是扩展视野。这是一些示例代码:

package MyApp::View::HTML;
use Moose;
use MooseX::Types::Moose qw( ArrayRef Str );
use namespace::autoclean;    

extends 'Catalyst::View::TT';

has common_assets => (
    traits  => [qw( Array )],
    isa     => ArrayRef[Str],
    handles => {
        common_assets => 'elements',
    },
);

before process => sub {
    my ($self, $ctx) = @_;

    $ctx->assets->include($_)
        for $self->common_assets;
};

1;

然后您可以使用如下内容对其进行配置:

<view HTML>
    common_assets foo.css
    common_assets bar.js
</view>

There is no context object yet during application setup, since the $c represents the current request.

If you are using Chained, you can do the call in your root chain action. If you use the non-Chained action types like Local, Path, etc. you can put a begin action in your root controller.

The most correct way in my opinion is however to extend the view. Here's some example code:

package MyApp::View::HTML;
use Moose;
use MooseX::Types::Moose qw( ArrayRef Str );
use namespace::autoclean;    

extends 'Catalyst::View::TT';

has common_assets => (
    traits  => [qw( Array )],
    isa     => ArrayRef[Str],
    handles => {
        common_assets => 'elements',
    },
);

before process => sub {
    my ($self, $ctx) = @_;

    $ctx->assets->include($_)
        for $self->common_assets;
};

1;

Then you can configure it with something like this:

<view HTML>
    common_assets foo.css
    common_assets bar.js
</view>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文