Perl 的模板工具包可以对未定义的值发出警告吗?
有没有办法让 Perl 的 Template
对我尝试使用 GET
指令(通过 [% %]
)在 模板::流程
?
默认行为是忽略并继续。 如果可能的话,我想仅在未定义值的情况下发出警告,并将消息记录到 STDERR。
Is there a way to make Perl's Template
display warnings for all undefined values that I attempt to use the GET
directive on (via [% %]
) during Template::process
?
The default behavior is to ignore and move on. I'd like to warn only in the case of undefined values, if possible, and to log messages to STDERR.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找:
(来自 http://search.cpan.org/ dist/Template-Toolkit/lib/Template/Manual/Config.pod。)
如果你想对异常进行一些特殊处理,你需要 捕获它或替换
__DIE__
信号处理程序。让我们把它们放在一起:
输出是:
我的方法是使用 Template 类的两个不同实例:
$debug_tt
,其中打开并隐藏了DEBUG_UNDEF
标志它的输出位于$output
变量中。$tt
这是一个普通实例,默认情况下将其输出打印到STDOUT
。两个实例都使用存储在
$template
中的相同模板以及存储在$vars
中的相同变量哈希。$debug_tt
包装在eval
中以避免过早退出,如果$debug_tt->error()
为 true,则会发出警告。$tt
正常执行。 我认为这满足了您的主要要求,尽管它可能效率不高。 我们需要使用此方法解析$template
两次。我对此的一些想法:
如果
Template::Toolkit
使用Carp
那就太好了,这样我们就可以获得有关警告的更多背景信息.人们可能可以从 Template 派生一个类,该类会在出错时发出警告而不是死亡。 我不想这样做。
根据模板的设置方式,一次输入一行可能是有意义的,这样您就可以在发现未定义的值时发出行号。
应该可以更改模板来测试自己的错误,并在面对未定义的值时发出更明智的文本。
应该可以更改
You are looking for:
(From http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Config.pod.)
If you want to do some special handling of the exception, you'll need to catch it or replace the
__DIE__
signal handler.Let's put it together:
The output is:
My approach was to use two different instances of the Template class:
$debug_tt
which has theDEBUG_UNDEF
flag turned on and hides its output in the$output
variable.$tt
which is a vanilla instance and prints its output toSTDOUT
as is the default.Both instances use the same template stored in
$template
and the same variable hash stored in$vars
.$debug_tt
is wrapped in aneval
to avoid exiting prematurely and a warning is emitted if$debug_tt->error()
is true.$tt
is executed normally. I think this satisfies your main requirements although it probably isn't efficient. We need to parse$template
twice using this method.Some thoughts I had working on this:
It would have been nice if
Template::Toolkit
had usedCarp
so that we could get a bit more context on the warning.One could probably derive a class from Template that would
warn
instead ofdie
on error. I didn't feel like doing that.Depending on how your templates are set up, it might make sense to feed it in one line at a time so that you could emit line numbers when an undefined value is found.
It should be possible to alter the templates to test for their own errors and emit more sensible text in the face of undefined values.
是的。 如果您将 DEBUG 选项传递给
Template->new
,TT 会警告您有关未定义的值。请参阅此处的文档: http://search.cpan .org/dist/Template-Toolkit/lib/Template/Manual/Variables.pod
Yes. If you pass the DEBUG option to
Template->new
, TT will warn you about undefined values.See the docs here: http://search.cpan.org/dist/Template-Toolkit/lib/Template/Manual/Variables.pod