Mojolicious路由(十一)

一、格式

像.html和.txt这样的文件扩展名会被自动检测到,并以stash关键字format的值存储。

# /foo      -> {controller => 'foo', action => 'bar'}
# /foo.html -> {controller => 'foo', action => 'bar', format => 'html'}
# /foo.txt  -> {controller => 'foo', action => 'bar', format => 'txt'}
$r->get('/foo')->to('foo#bar');

例如,允许不同格式的多个模板共享相同的操作代码。限制性占位符也可以用来限制允许的格式。

# /foo.txt -> undef
# /foo.rss -> {controller => 'foo', action => 'bar', format => 'rss'}
# /foo.xml -> {controller => 'foo', action => 'bar', format => 'xml'}
$r->get('/foo' => [format => ['rss', 'xml']])->to('foo#bar');

格式化值也可以传递给Mojolicious::Controller中的“url_for”。

# /foo/bar.txt -> {controller => 'foo', action => 'bar', format => 'txt'}
$r->get('/foo/:action')->to('foo#')->name('baz');

# Generate URL "/foo/bar.txt" for route "baz"
my $url = $c->url_for('baz', action => 'bar', format => 'txt');

或者,我们可以使用特殊类型的限制性占位符禁用格式检测,它会被嵌套路由继承,然后根据需要重新启用它。

# /foo      -> {controller => 'foo', action => 'bar'}
# /foo.html -> undef
$r->get('/foo' => [format => 0])->to('foo#bar');

# /foo      -> {controller => 'foo', action => 'bar'}
# /foo.html -> undef
# /baz      -> undef
# /baz.txt  -> {controller => 'baz', action => 'yada', format => 'txt'}
# /baz.html -> {controller => 'baz', action => 'yada', format => 'html'}
# /baz.xml  -> undef
my $inactive = $r->under([format => 0]);
$inactive->get('/foo')->to('foo#bar');
$inactive->get('/baz' => [format => ['txt', 'html']])->to('baz#yada');

标签