Perl 和 Catalyst:从模型访问 maketext

Perl and Catalyst: accessing maketext from a model

编辑以澄清/反映我一直在尝试的内容:

我正在使用 CatalystX::I18N::* 以便能够使我的网站国际化。我的效果很好,我的网站文本来自 $c->maketext().

但是,我一直在尝试从我的数据库模型访问这些代码(以便在创建/更新之前检查输入时生成例如成功或失败消息)并且我很挣扎。

根据CatalystX::I18N docs, CatalystX::I18N::Maketext is a 'Helpful wrapper around Locale::Maketext。也可以在 Catalyst 之外使用。

我已按照指示进行 MyApp::Maketext 设置:

package MyApp::Maketext;

use strict;
use warnings;
use parent qw(CatalystX::I18N::Maketext);

1;

我有一个小测试脚本 运行,其设置是这样的:

#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../lib";
use TopTable::Maketext;
use Path::Class::Dir;

my $dir = Path::Class::Dir->new( "$Bin/..", "root", "locale" );
TopTable::Maketext->load_lexicon(
  locales => ["en_GB"], # Required
  directories => [$dir], # Required
  gettext_style => 0, # Optional, Default 1
);

然后我尝试两种不同的方法来获取 maketext() 方法的句柄:

my $lang = TopTable::Maketext->get_handle;
printf "%s\n", $lang->maketext( "menu.title.news" );

给出以下结果:

Can't call method "maketext" on an undefined value at bin\maketext-demo.pl line 23.

如果我将 ->get_handle 换成 ->new:

my $lang = TopTable::Maketext->new;
printf "%s\n", $lang->maketext( "menu.title.news" );

我得到以下信息:

maketext doesn't know how to say:
menu.title.news
as needed at bin\maketext-demo.pl line 23.

我有点不知道接下来要尝试什么!非常感谢任何人可以提供的任何指示。

克里斯

我终于明白了这一点 - 这是最终起作用的代码:

#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../lib";
use Data::Dumper::Concise;
use TopTable::Maketext;
use Config::ZOMG;
use Path::Class::Dir;

my $tt_config = Config::ZOMG->new( name => 'TopTable' );
my $config_hash = $tt_config->load;

my (@locales, %inhertiance, $config);
$config = $config_hash->{I18N}{locales};
foreach my $locale (keys %$config) {
  push(@locales, $locale);
  $inhertiance{$locale} = $config->{$locale}{inherits} if defined $con
+fig->{$locale}{inherits};
}

my $dir = Path::Class::Dir->new( "$Bin/..", "root", "locale" );
TopTable::Maketext->load_lexicon(
  locales => \@locales,
  directories => [$dir],
  gettext_style => 1,
  inheritance => \%inhertiance,
);

my $lang = TopTable::Maketext->get_handle( "en_GB" );
printf "%s\n", $lang->maketext( "menu.title.league-tables", "Division Three" );

1;

这给出了正确的值:

League Tables for Division Three

感谢您容忍我的垃圾邮件!