Liquid:我可以从数组中获取随机元素吗? [英] Liquid: Can I get a random element from an Array?

查看:165
本文介绍了Liquid:我可以从数组中获取随机元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数组中选择随机元素-使用Liquid/Jekyll可以吗?

I'm trying to pick a random element from an array -- is this possible using Liquid/Jekyll?

我可以创建一个数组-并访问给定的索引...但是有没有办法洗牌"该数组然后选择一个索引,从而从该数组中获取一个随机元素?

I can create an array -- and access a given index ... but is there a way to "shuffle" the array and then select an index, and thus get a random element from the array?

prefix: ["Foo", "Bar", "Baz"]
---

{{ page.prefix[1] }}

# outputs "Bar"

推荐答案

液体没有用于从数组或整数间隔中选择随机元素的过滤器.

Liquid doesn't have a filter for picking a random element from an array or an integer interval.

如果您希望Jekyll这样做,则必须创建一个扩展程序以添加该液体过滤器.

If you want Jekyll to do that, you would have to create an extension to add that liquid filter.

但是,我必须指出,这样做每次生成页面时都会选择一个随机元素,但并非每次查看页面时都会选择一个随机元素.

However, I must point out that doing so would pick a random element every time the page is generated, but not every time the page is viewed.

如果您希望每次访问页面时获得不同的随机值,那么最好的选择是使用javascript,然后让客户端选择一个随机值.不过,您可以使用Liquid来生成相关的javascript.

If you want to get different random values every time you visit a page, your best option is using javascript and letting the client pick a random value. You can use liquid to generate the relevant javascript though.

这篇关于Liquid:我可以从数组中获取随机元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆