Dancer2
Dancer2 copied to clipboard
Allow Mutable serializer to render templates?
It could be useful to return a data structure from a route handler and have it automatically serialized to JSON/XML or rendered in a template depending on Accept: header supplied by the user. Right now we have a Mutable serializer which chooses a serializer based on headers, but no way to render a template if user asks for text/html instead.
Mojolicious has respond_to helper which achieves this. Could Mutable serializer be extended to allow similar things? Right now it's not obvious how it would determine the template to render.
Feel free to point out the obvious solution I am missing, talk me out of returning HTML or JSON from the same route, or suggest alternative API designs. I can help with the implementation too, once there is consensus on how it should behave.
If a serializer is declared, Dancer2 is going to use it. The usual advice is to use the send_as keyword if there is only a handful or routes needing special handling, or split your app. Neither approach really fits if you want to honour the Accept header in all routes.
A new keyword such as respond_to would be a better fit into Dancer2's design rather than adapting the mutable serializer. New keywords can be initially implemented as a plugin, then when the design is ready be incorporated into core if the demand is there for it.
There is some prior art on cpan too, such as Dancer2::Plugin::HTTP::ContentNegotiation which I haven't used, but worth a look.
This is a really interesting design topic, but we need to discuss this in some detail. We need to flesh this out further, and it might open some new possibilities in the framework. We'll follow up with this in some greater detail in the next few weeks. Thanks for the idea!