How do I get a random number in template toolkit?

守給你的承諾、 提交于 2020-01-03 10:49:21

问题


I want to get a random number using template toolkit. It doesn't have to be particularly random. How do I do it?


回答1:


From this post at Slashcode:

[slash@yaz slash]$ perl -MSlash::Test -leDisplay
[%
digits = [ 0 .. 9 ];
anumber = digits.rand _ digits.rand _ digits.rand;
anumber;
%]
^D
769



回答2:


Hmm, you might have issues if you don't have (or cannot import) Slash::Test. From a "vanilla" installation of TT, you can simply use the Math plugin:

USE Math;
GET Math.rand; # outputs a random number from 0 to 1

See this link in the template toolkit manual for more information on the Math plugin and the various methods.

Update: Math.rand requires a parameter. Therefore to get a random number from 0 to 1, use:

GET Math.rand(1);


来源:https://stackoverflow.com/questions/722562/how-do-i-get-a-random-number-in-template-toolkit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!