【问题标题】:Passing variable to layout template in Mojolicious将变量传递给 Mojolicious 中的布局模板
【发布时间】:2021-09-06 04:10:27
【问题描述】:

我正在尝试使用存储变量设置状态页面的刷新率 所以我在控制器中有以下代码来呈现页面:

my $refreshrate = 10;
$self->stash( refreshrate => $refreshrate);
$self->render();

在我拥有的 html 模板中:

% layout 'refreshLayout', title => 'A title';
% content_for refresh => begin
% end
<div>....body content .../<div>

在我的布局模板中:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
    <meta charset="UTF-8"/>
    <meta http-equiv="refresh" content="<%= refreshrate %>"/>
        .....
    <title><%= title %></title>
 </head>
  <body><%= content %></body>
</html>

我总是以刷新元标记的内容属性中没有值的页面结束。 看起来refreshrate 替换不起作用。 但是,contenttitle 替换都可以。

那么我在这里做错了什么? 当我们在这里时,为什么在布局模板中我们确实使用 (而不是 $content) 而在常规页面的模板中,我们使用更符合逻辑的 布局模板中的替换与主页模板中的替换如何工作?

【问题讨论】:

    标签: perl mojolicious


    【解决方案1】:

    存储值在您的模板中显示为 perl 变量。 (title 很特别,因为它也是一个默认的辅助函数)。 如果您想将 refreshrate 的存储值传递给布局,则必须将其添加到您的 layout() args:

    use Mojolicious::Lite;
    
    get '/' =>  sub  {
        my $c = shift;
        $c->stash (refreshrate => 10),
        $c->render(template => 'foo/bar')};
    
    app->start;
    __DATA__
    
    @@ foo/bar.html.ep
    % layout 'mylayout', title => 'Hi there',refreshrate => $refreshrate;
    Hello World!
    
    @@ layouts/mylayout.html.ep
    <!DOCTYPE html>
    <html>
        <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
        <meta charset="UTF-8"/>
        <meta http-equiv="refresh" content="<%= $refreshrate %>"/>
        <title><%= $title %></title></head>
      <body><%= content %></body>
    </html>
    

    查看Rendering doc中的布局

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 2019-04-03
      • 2011-05-08
      相关资源
      最近更新 更多