3

I am attempting to write a somewhat generic layout that can take as a parameter either an array of strings or a hash of options, so you can either do:

option:
    - "<li><b>One:</b> This is</li>"
    - "<li><b>Two:</b> Raw HTML</li>"

Or you can do:

option:
    One: This is
    Two: a mapping

The reason I want to support both of these is that this is a public layout and the first option is already supported, but I would prefer to use the second option, so I want something of a deprecation period where both versions are supported.

I saw in check if a variable is type of string or array in liquid that there's a way to determine if something is an array or a string, but both arrays and hashes have a first attribute! A practical way to re-use this function might be to check if the first element of the variable also has a first attribute, like so:

{% if site.option.first %}
    {% if site.option.first.first %}
        hash
    {% else %}
        array
    {% endif %}
{% else %}
    Something else!
{% endif %}

But this seems a bit unwieldy and a bit of a hack - plus it will give the wrong answer if passed an array of arrays (even though "array of arrays" is not considered a valid input in this case). Is there a better way to do this?

Paul
  • 10,381
  • 13
  • 48
  • 86

1 Answers1

0

For arrays you know will not include numbers, you can use the following:

---
arr:
  - ""
  - "2"
  - three
  - null
hash:
  foo: bar
  baz: null
  "0": 1
string: "a string"
---


nil: {{ page.nil_prop | map: "" | join: "," | size }} # 0
str: {{ page.string | map: "" | join: "," | size }} # 0
hash: {{ page.hash | map: "" | join: "," | size }} # 0
arr: {{ page.arr | map: "" | join: "," | size }} # 3

However, if a number sneaks into your array, you get Liquid Exception: no implicit conversion of String into Integer.

This is on Jekyll 3.8.

Steven Kalt
  • 1,116
  • 15
  • 25