perl - 如何在独立的 Perl 脚本中使用 Mojolicious 渲染?

标签 perl templating mojolicious

我要渲染 .html.ep在发送电子邮件并从 cron 运行的独立脚本中使用 Mojolicious 渲染引擎的模板:

#!/usr/bin/perl

use feature ':5.10';

use Mojo::Base -strict;
use Mojolicious::Renderer;
use Data::Dumper;


my $renderer = Mojolicious::Renderer->new();
push @{$renderer->paths}, '/app/templates';

my $template = $renderer->get_data_template({
    template => 'template_name',
    format => 'html',
    handler => 'ep'
});

print Dumper($template) . "\n";
    
但是,$template总是未定义的。
模板文件为 /app/templates/template_name.html.ep .
我究竟做错了什么?

最佳答案

您正在使用 get_data_template 来自 Mojo::Renderer,用于从 __DATA__ 加载模板当前源代码文件的部分。

事实上,Mojo::Renderer 是用错了 .你想要Mojo::Template ,作为一个模块的独立模板引擎。

use Mojo::Template;

my $mt = Mojo::Template->new( vars => 1 );
my $email_body = $mt->render_file( 'test.html.ep', { one => 1, two => 2 } );
say $email_body;

使用 test.html.ep:
The magic numbers are <%= $one %> and <%= $two %>.

输出:
The magic numbers are 1 and 2.

option vars 很重要,因此它接受命名变量而不是参数列表。

关于perl - 如何在独立的 Perl 脚本中使用 Mojolicious 渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120196/

相关文章:

perl - 如何在 Perl 中比较日期字符串

c++ - 在 64 位 CENTO 上重复安装 Perl

javascript - 需要 kendoUI 模板类型 ="text/x-kendo-template"?

perl - '%p' 和 'my %p' 之间的区别?

perl - 测试有状态的 Mojolicious 应用程序

perl - 为什么 Perl 自动激活对 ->@* 不起作用,但对 ->@[0] 却起作用?

linux - Perl 目录查找器不起作用?

html - node.js - 将焊接与 express 一起使用?

Java jinja/django 类 html 模板

perl - 如何获取 Mojolicious::Lite 选择的端口?