Search code examples
perlmojolicious

How can I register a rendering plugin for Mojolicious?


I am having a hard time making a rendering plugin for Mojolicious work. My plugin looks like this (for now):

package Mojolicious::Plugin::Renderer::XML;
use Mojo::Base 'Mojolicious::Plugin';

sub register {
    my ($self, $app, $conf) = @_;
    $app->renderer->add_handler('xml' => sub {
                    ${$_[2]} = 'say something';
                    return 1;
                } );
}
1;

and in the application I have:

plugin 'Renderer::XML';

and later

get '/x/xml' => sub {
    my $c = shift;
    $c->render( xml => 'bar' );
};

I can see that the plugin gets registered (dumping the list of renderer->handlers, but it looks like the sub never even gets called (I inserted debugging output to check). I tried doing the same from inside the app as described here, but no results.

Does anyone have a better clue than me?


Solution

  • Take a look at the render sub implementation in Mojolicious::Renderer. You will see that the accepted data types are fixed. There is no way to add more with just a plugin.

    Now look at Mojolicious::Plugin::XML::Loy. He had to create a render_xml helper. Good enough!