我能否使用Template Toolkit找出变量是否是一个数组?(Can I find out if variable is an array using Template Toolkit?)

编程入门 行业动态 更新时间:2024-10-24 12:21:22
我能否使用Template Toolkit找出变量是否是一个数组?(Can I find out if variable is an array using Template Toolkit?)

我将多选框的结果传递给页面,以便可以在屏幕上显示选择。 由于它是多选的,因此结果可以是标量或数组引用。 有没有办法找出这个问题? 我在网上找不到任何东西,但我想可能有一个.array或.array_ref标记可用于验证。 我正在使用模板工具包,Perl和舞者。

所以这就是我得到的标量:

<% IF multitext %> Text: <% multitext %> <% END %>

我想要的是类似...

<% IF multitext %> <% IF multitext.array_ref %> <!-- whatever works! --> <% FOREACH text IN multitext %> Text: <% text %> <% END %> <% ELSE %> Text: <% multitext %> <% END %> <% END %>

I'm passing the results of a multi-select box to a page so that the selections can be shown on screen. As it's multi-select, the result can either be a scalar or an array reference. Is there a way of finding this out? I can't find anything online, but I thought there might be a .array or .array_ref token that could be used for validation. I'm using Template Toolkit, Perl and Dancer.

So here is what I've got for a scalar:

<% IF multitext %> Text: <% multitext %> <% END %>

What I want is something like...

<% IF multitext %> <% IF multitext.array_ref %> <!-- whatever works! --> <% FOREACH text IN multitext %> Text: <% text %> <% END %> <% ELSE %> Text: <% multitext %> <% END %> <% END %>

最满意答案

如果<%- multitext.0 -%>返回一个非零值,则它是一个arrayref。

如果<%- multitext.keys.size -%>返回非零值,则为hashref。

我通常处理它的方式是强制它成为一个数组,如果它是一个标量,例如:

<%- SET items = multitext.0 ? multitext : [ multitext ]; FOREACH item IN items; ... END; -%>

If <%- multitext.0 -%> returns a non-zero value, it's an arrayref.

If <%- multitext.keys.size -%> returns a non-zero value, it's a hashref.

The way I usually handle it is to force it to be an array if it's a scalar, eg:

<%- SET items = multitext.0 ? multitext : [ multitext ]; FOREACH item IN items; ... END; -%>

更多推荐

本文发布于:2023-07-29 20:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1319549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是一个   数组   变量   Toolkit   Template

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!