Mojolicious-Plugin-PetalTinyRenderer
view release on metacpan or search on metacpan
lib/Mojolicious/Plugin/PetalTinyRenderer.pm view on Meta::CPAN
$$output = '';
my $log = $c->app->log;
if (defined $inline) {
$log->debug(qq{Rendering inline template "$name".});
$$output = $self->_render_xml($inline, $c, $name);
}
else {
if (defined(my $path = $renderer->template_path($options))) {
$log->debug(qq{Rendering template "$name".});
my $encoding = $self->config->{encoding} // ":encoding(UTF-8)";
if (open my $file, "<$encoding", $path) {
my $xml = join "", <$file>;
$$output = $self->_render_xml($xml, $c, $name);
close $file;
}
else {
$log->debug(qq{Template "$name" ($path) not readable.});
return undef;
}
}
elsif (my $d = $renderer->get_data_template($options)) {
$log->debug(qq{Rendering template "$name" from DATA section.});
$$output = $self->_render_xml($d, $c, $name);
}
else {
$log->debug(qq{Template "$name" not found.});
return undef;
}
}
return 1;
}
sub _render_xml {
my ($self, $xml, $c, $name) = @_;
my $deldiv = 0;
if ($xml !~ /\bxmlns:/) {
$xml = "<div $tal_ns>$xml</div>";
$deldiv = 1;
}
my $template = Petal::Tiny::_Mojo->new($xml);
my $helper = Mojolicious::Plugin::PetalTinyRenderer::Helper->new(ctx => $c);
my $html;
try {
$html = $template->process(%{$c->stash}, c => $c, h => $helper);
}
catch {
my $validator;
eval "use XML::Validate; \$validator = XML::Validate->new(Type => 'LibXML');";
if ($validator) {
$xml =~ s/<!DOCTYPE.*?>//;
if ($validator->validate($xml)) {
die "Petal::Tiny blew up handling '$name', and XML::Validate reports the XML is fine.\n\n$_";
}
else {
my $e = $validator->last_error;
my $message = $e->{message} // "";
die "Petal::Tiny blew up handling '$name', and XML::Validate reports:\n\n$message";
}
}
else {
die "Petal::Tiny blew up handling '$name'. Install XML::Validate and XML::LibXML for better diagnostics.\n\n$_";
}
};
if ($deldiv) {
$html =~ s,\A<div>,,;
$html =~ s,</div>\z,,;
}
return $html;
}
1;
package
Petal::Tiny::_Mojo;
use Mojo::Base 'Petal::Tiny';
use Scalar::Util 'blessed';
sub reftype {
my ($self, $obj) = @_;
return 'ARRAY' if blessed $obj and $obj->isa('Mojo::Collection');
return $self->SUPER::reftype($obj);
}
1;
package
Mojolicious::Plugin::PetalTinyRenderer::Helper;
use Mojo::Base -base;
our $AUTOLOAD;
__PACKAGE__->attr('ctx');
# stolen from Mojolicious::Plugin::TtRenderer::Helper
sub AUTOLOAD {
my $self = shift;
my $method = $AUTOLOAD;
return if $method =~ /^[A-Z]+?$/;
return if $method =~ /^_/;
return if $method =~ /(?:\:*?)DESTROY$/;
$method = (split '::' => $method)[-1];
die qq/Unknown helper: $method/ unless $self->ctx->app->renderer->helpers->{$method};
( run in 1.991 second using v1.01-cache-2.11-cpan-99c4e6809bf )