Mojolicious模板渲染(十一)

一、Content代码块

content_for是一个非常有用的helper。当我们的模板中存在多处需要填写的content时,我们可以给除了默认的content以外的其他content命名。之后,在我们的模板中只需要用content_for调用命名content来填写内容即可:

use Mojolicious::Lite;
 
get '/' => 'foo';
 
app->start;
__DATA__
 
@@ foo.html.ep
% layout 'mylayout';
% content_for header => begin
 #填写header中的内容
  <meta http-equiv="Content-Type" content="text/html">
% end
<div>Hello World!</div>
% content_for header => begin
 #可以填写多次
  <meta http-equiv="Pragma" content="no-cache">
% end
 
@@ layouts/mylayout.html.ep
<!DOCTYPE html>
<html>
  <head><%= content 'header' %></head>
 #定义了一个header content。
  <body><%= content %></body>
</html>

二、表单forms

我们可以使用Mojolicious::Plugin::TagHelpers模块中form_for helper快速方便的生成form表单代码。由于大多数浏览器只允许使用GET和POST提交表单,而不允许使用PUT或DELETE等请求方法,我们如果想使用这些方法可以通过_method查询参数来欺骗表单。

use Mojolicious::Lite -signatures;
 
get '/' => 'form';
 
# PUT  /nothing
# POST /nothing?_method=PUT
put '/nothing' => sub ($c) {
 
  # Prevent double form submission with redirect
  my $value = $c->param('whatever');
  $c->flash(confirmation => "We did nothing with your value ($value).");
  $c->redirect_to('form');
};
 
app->start;
__DATA__
 
@@ form.html.ep
<!DOCTYPE html>
<html>
  <body>
    % if (my $confirmation = flash 'confirmation') {
      <p><%= $confirmation %></p>
    % }
    %= form_for nothing => begin
      %= text_field whatever => 'I ♥ Mojolicious!'
      %= submit_button
    % end
  </body>
</html>

Mojolicious::Plugin::DefaultHelpers中的helper函数”flash”和Mojolicious::Plugin::DefaultHelpers中的”redirect_to”经常一起使用,以防止双表单提交,这样用户就可以收到一条确认消息,当他们决定重新加载重定向到的页面时,该消息就会消失。

标签