root/lang/perl/NanoA/trunk/lib/NanoA/TemplateLoader.pm @ 24573

Revision 24573, 1.5 kB (checked in by kazuho, 5 years ago)

automatically detect if string is already escaped

  • Property svn:keywords set to Id
Line 
1package NanoA::TemplateLoader;
2
3use strict;
4use warnings;
5use utf8;
6
7use base qw(NanoA);
8
9sub __load {
10    my ($config, $module, $path) = @_;
11    if (__use_cache($config, $path)) {
12        NanoA::load_once($config->mt_cache_dir . "/$path.c", $path);
13        return $module;
14    }
15    my $code = __compile($path, $module);
16    local $@;
17    eval $code;
18    die $@ if $@;
19    __update_cache($config, $path, $code)
20        if $config->mt_cache_dir;
21    NanoA::loaded($path, 1);
22}
23
24sub __compile {
25    my ($path, $module) = @_;
26    NanoA::require_once('MENTA/Template.pm');
27    my $t = MENTA::Template->new;
28    $t->parse(NanoA::read_file($path));
29    $t->build();
30    my $code = $t->code();
31    $code = << "EOT";
32package $module;
33use strict;
34use warnings;
35use utf8;
36use base qw(NanoA::TemplateLoader);
37NanoA::__insert_methods(__PACKAGE__);
38sub run {
39    my (\$app, \$c) = \@_;
40    raw_string($code->());
41}
421;
43EOT
44;
45    $code;
46}
47
48sub __update_cache {
49    my ($config, $path, $code) = @_;
50    my $cache_path = $config->mt_cache_dir;
51    foreach my $p (split '/', $path) {
52        mkdir $cache_path;
53        $cache_path .= "/$p";
54    }
55    $cache_path .= '.c';
56    open my $fh, '>:utf8', $cache_path
57        or die "failed to create cache file $cache_path";
58    print $fh $code;
59    close $fh;
60}
61
62sub __use_cache {
63    my ($config, $path) = @_;
64    return unless $config->mt_cache_dir;
65    my @orig = stat $path
66        or return;
67    my @cached = stat $config->mt_cache_dir . "/$path.c"
68        or return;
69    return $orig[9] < $cached[9];
70}
71
72"ENDOFMODULE";
73
Note: See TracBrowser for help on using the browser.