使用Perl的Template.pm,如何从数组中选择随机元素并将其输出?
假设我的模板中有以下内容:
[%- pages = [ 'one', 'two', 'three' ] -%]
<p>Go to page [%- ... -%]</p>
假设 EVAL_PERL
未设置(即,我无法使用 [%- PERL -%]
块),我需要在上面的 [%- ... -%]
中放入什么才能获得以下输出?
<p>Go to page "a randomly picked element of pages"</p>
Suppose I have the following in my template:
[%- pages = [ 'one', 'two', 'three' ] -%]
<p>Go to page [%- ... -%]</p>
Assuming EVAL_PERL
is not set (i.e., I cannot use a [%- PERL -%]
block), what do I need to put inside the [%- ... -%]
above so as to get the following output?
<p>Go to page "a randomly picked element of pages"</p>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,模板中不支持
rand
,因此您必须通过其他代码(例如 斜杠)或使用 Template::Plugin::Math,例如:输出:
There isn't any support for
rand
by default in Template, so you have to either import it via some other code (like Slash) or use Template::Plugin::Math, e.g.:Output:
如果我必须做任何复杂的事情,我只需使用
[%PERL%]
部分并跳过 Template Toolkit 语法。此外,我在控制器中尽可能多地计算并传递要使用的值的数据结构。我尽量不在模板中选择值或创建新值。一旦将逻辑移入模板,当您有另一组模板时,就必须重新定义它。
If I have to do anything complex, I just use
[%PERL%]
sections and skip the Template Toolkit syntax.Additionally, I figure out as much as I can in the controller and pass in a data structure of the values to use. I try to never select values or create new values in the template. Once you move logic into the template, you have to redefine it when you have another set of templates.