3

如何添加一个vmethod使用 Dancer 时

如果没有办法,我该如何添加一个函数/如何执行一个添加到令牌中的函数的引用/?

4

3 回答 3

2

要在Dancer中向 TT添加自定义 vmethod ,需要对直接 TT 包变量进行一些处理。我确实希望Dancer::Template对象提供对底层模板对象的访问。

这是可以进入舞者路线的片段:

package mydancerapp;

use Dancer qw(:syntax);

# make sure TT module is loaded since Dancer loads it later in the request cycle
use Template::Stash;

# create list op vmethod, sorry its pretty trivial
$Template::Stash::LIST_OPS->{ uc_first  } = sub {
    my $list = shift;
    return [ map { ucfirst } @$list ];
);

最好将其移动到它自己的模块中mydancerapp::TT,或者mydancerapp::TT::VMethods然后将其加载到您的主应用程序类中。

然后你可以在你的模板中使用它,比如:

# in route
get '/' => sub {
    template 'index', { veggies => [ qw( radishes lettuce beans squash )] };
};

# in template: views/index.tt
<p>[% veggies.uc_first.join(',') %]</p>

如果进展顺利,那么您应该Radishes,Lettuce,Beans,Squash在输出中看到::)

于 2011-10-18T14:43:43.710 回答
1

我不确定是否要添加 vmethod,但我认为第二件事可以这样完成:

hook 'before_template' => sub {
    my $tokens = shift;
    $tokens->{myfunction} = sub { ... };         #  OR ...
    $tokens->{otherfunction} = \&other_func;
};
于 2011-09-22T14:25:40.090 回答
0

在 Dancer2 中,您可以这样做:

hook before => sub {
    my ( $app ) = @_;

    $app->template_engine->engine->context->define_vmethod( 'list' => 'uc_first' => sub {
        my $list = shift;
        return [ map { ucfirst } @$list ];
    });
};
于 2016-02-13T19:44:23.727 回答