summary refs log tree commit diff
path: root/lib/Dancer/Plugin/I18n.pm
blob: 67c57ec67e99ab56f30196fab82263162f08100c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package Dancer::Plugin::I18n;

use strict;
use warnings;
use Dancer::Plugin;

use I18N::LangTags;
use I18N::LangTags::Detect;

our $VERSION = '0.01';

my @languages;
my $i18n_package;

add_hook(
    before_dispatch => sub {
        my $request = shift;
        @languages = ('en');
        push @languages, I18N::LangTags::implicate_supers(
            I18N::LangTags::Detect->http_accept_langs(
                scalar $request->header('Accept-Language')
            )
        );
        my $app = "TestApp";
        $i18n_package = $app."::I18N";
        eval "package $i18n_package; use base 'Locale::Maketext'; 1;";
        die "Impossible to load I18N plugin : $@" if $@;
    }
);

add_hook(
    before_template => sub {
        my ( $view, $tokens ) = @_;
        $tokens->{l}         = sub { localize(@_) };
        $tokens->{languages} = sub { languages(@_) };
    },
);

register languages => sub { languages(@_); };
register l         => sub { localize(@_); };

sub languages {
    my @lang = shift;
    return $languages[0] unless @lang;
    unshift @languages, @lang;
    return;
}

sub localize {
    if ( $i18n_package && ( my $h = $i18n_package->get_handle(@languages) ) )
    {

        return $h->maketext(@_);
    }
    else {
        return join '', @_;
    }
}

register_plugin;

1;
__END__

=head1 NAME

Dancer::Plugin::I18n - Intenationalization for Dancer

=head1 SYNOPSIS

    package myapp::I18N::fr;
    use base 'myapp::I18N';
    our %Lexicon = ( hello => 'bonjour' );
    1;

    package myapp;
    use Dancer;
    use Dancer::Plugin::I18n;
    get '/' => sub { template 'index' };

    # index.tt
    hello in <% languages %> => <% l('hello') %>
    # or
    <% languages('fr') %>This is an <% l('hello') %>

=head1 DESCRIPTION

Dancer::Plugin::I18n add L<Locale::Maketext> to your L<Dancer> application

=head1 METHODS

=head2 languages

=head2 l

=head1 AUTHOR

franck cuny E<lt>franck@lumberjaph.netE<gt>

=head1 SEE ALSO

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut