【问题标题】:How to add a vmethod to template toolkit when using Dancer?使用 Dancer 时如何向模板工具包添加 vmethod?
【发布时间】:2011-11-21 04:16:30
【问题描述】:

使用Dancer时如何在模板工具包中添加vmethod

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

【问题讨论】:

    标签: perl template-toolkit dancer


    【解决方案1】:

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

    hook 'before_template' => sub {
        my $tokens = shift;
        $tokens->{myfunction} = sub { ... };         #  OR ...
        $tokens->{otherfunction} = \&other_func;
    };
    

    【讨论】:

      【解决方案2】:

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

      这是可以进入 Dancer 路线的 sn-p:

      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::TTmydancerapp::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。 :)

      【讨论】:

      • 我尝试过这样的事情,但它没有用,所以我发布了这个问题。现在它可以工作了^^
      【解决方案3】:

      在 Dancer2 中,您可以这样做:

      hook before => sub {
          my ( $app ) = @_;
      
          $app->template_engine->engine->context->define_vmethod( 'list' => 'uc_first' => sub {
              my $list = shift;
              return [ map { ucfirst } @$list ];
          });
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-24
        • 1970-01-01
        • 2013-06-06
        • 2011-12-21
        • 2013-01-27
        • 2011-12-26
        • 1970-01-01
        相关资源
        最近更新 更多