Mojolicious初学(九)
一、Formats渲染格式
通常关于Formats格式,Mojolcious会通过template文件扩展名自动判定,例如.html。Mojolicious会自动的生成正确的模板,以及Content-Type的header值:
use Mojolicious::Lite -signatures; # /detection 默认情况下,会返回html文件 # /detection.html 浏览器想要返回html文件 # /detection.txt 浏览器想要返回txt文件 get '/detection' => sub ($c) { $c->render(template => 'detected'); }; app->start; __DATA__ @@ detected.html.ep <!DOCTYPE html> <html> <head><title>Detected</title></head> <body>HTML was detected.</body> </html> @@ detected.txt.ep TXT was detected.
同时,我们可以严格限制返回的格式:
use Mojolicious::Lite -signatures; # /hello.json # /hello.txt get '/hello' => [format => ['json', 'txt']] => sub ($c) { #通过第一个=>后中括号增加一个键值对,限定只能返回json或txt格式 return $c->render(json => {hello => 'world'}) if $c->stash('format') eq 'json'; $c->render(text => 'hello world'); }; app->start;
我们也可以关闭格式检测:
use Mojolicious::Lite; #通过format => 0将格式检测关闭,也可以叫做锁死——只允许返回一个格式: # /hello get '/hello' => [format => 0] => {text => 'No format detection.'}; # Disable detection and allow the following routes to re-enable it on demand under [format => 0]; # /foo get '/foo' => {text => 'No format detection again.'}; # 通过将format指定唯一个类型,也可以其他锁死类型的作用: # /bar.txt get '/bar' => [format => 'txt'] => {text => ' Just one format.'}; app->start;
二、内容协商Content negotiation
当我们的前端页面,例如jquery ajax函数要求服务器返回json、xml格式,可以通过respond_to方法:
use Mojolicious::Lite -signatures; # /hello (Accept: application/json) # /hello (Accept: application/xml) # /hello.json # /hello.xml # /hello?format=json # /hello?format=xml get '/hello' => sub ($c) { $c->respond_to( #此处调用respond_to,可以根据浏览器发送来的Content-Type: application/json或 #Content-Type: application/xml返回json或xml格式信息。 json => {json => {hello => 'world'}}, xml => {text => '<hello>world</hello>'}, any => {data => '', status => 204} ); }; app->start;
我们还可以通过Mojolicious的types方法,轻松的修改MIME类型(http专用术语,自行百度):
app->types->type(rdf => 'application/rdf+xml');