作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要能够在 Mojolicious::Lite 应用程序中编写和调用我自己的子程序。但是,这样做的直观方法似乎不起作用。我给一位同事发了电子邮件,他对这个问题比我更有 Mojolicious 经验,他给我发送了以下代码:
#!/usr/bin/env perl
use Mojolicious::Lite;
# Documentation browser under "/perldoc"
plugin 'PODRenderer';
get '/' => sub {
my $self = shift;
$self->render('index');
};
sub factorial {
my $n = shift;
return $n ? $n * factorial($n - 1) : 1;
}
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!
Five factorial: <%= main::factorial(5) %>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
Undefined subroutine &main::factorial called at template index.html.ep from DATA section line 5, line 32.
最佳答案
正如 PerC 已经提到的,助手是向模板添加行为(或访问行为)的首选机制。由于他已经展示了该示例,因此我将补充说,您可以通过执行以下操作来混合两者(我正在删除 pod 渲染器插件,您不需要它)。
#!/usr/bin/env perl
use Mojolicious::Lite;
get '/' => sub {
my $self = shift;
$self->render('index');
};
sub factorial {
my $n = shift;
return $n ? $n * factorial($n - 1) : 1;
}
helper factorial => sub { shift; factorial(@_) };
app->start;
__DATA__
@@ index.html.ep
% layout 'default';
% title 'Welcome';
Welcome to the Mojolicious real-time web framework!
Five factorial: <%= factorial(5) %>
@@ layouts/default.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
关于perl - 如何在 Mojolicious::Lite 应用程序中使用我自己的子程序(全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22944341/
我是一名优秀的程序员,十分优秀!