Jekyll and Hash/Associative Arrays

Having just once again suffered through the dimly remembered pain of learning about Jekyll, Liquid, and hash (associative) arrays, I am recording it here to save myself the next time I go for a few years between dealing with it. Official documentation does not say this (enough?), I guess because they think, "They can't, so let's not bother talking about it." This leaves the experienced programmer new to Liquid going "I should be able to do this, why can't I just assign myHash = { one: 1, two: 2 } or ["one" => "1", "two" => "2"] or some combination of braces and quotes or other punctuation? Do I just have the syntax wrong???"

You can't. For some reason "they" don't want you to.

If you were trying to keep your data close to where you are using it in an _include, that's not possible because there's no front matter in _includes and you can't create/populate an associative array/hash table in regular code either. Hash tables or dictionaries can only be created/defined in YML files or front matter. So, define your hash array in the nearest _layout front matter, site _config.yml, or site _data/ if what you really want is to put it in the front matter of an _include.

  1. Hash arrays cannot be created within Jekyll+Liquid
    • vector arrays can
    • hash arrays can be created in front matter or .yml files

Hash Arrays vs Dictionaries

For some guidance on YML, there's the source from yaml.org and a shorter YML guide. A caveat on the shorter guide, however, don't put a "-" in front of dictionary keys. I'm not sure if that's a quirk of Jekyll-Liquid/Shopify Liquid though.

To access

dictionary:
  zero:
    number: "0"
  one:
    number: "1"
    adj: 
      - "first"
      - "unary"
    ordinal: "primary"
  two:  
    number: "2"
    adj: 
      - "second"
      - "dual"
      - "binary"
    ordinal: "secondary"
dictionary {"zero"=>{"number"=>"0"}, "one"=>{"number"=>"1", "adj"=>["first", "unary"], "ordinal"=>"primary"}, "two"=>{"number"=>"2", "adj"=>["second", "dual", "binary"], "ordinal"=>"secondary"}}

Getting at the data within. Note that the first thing we try doesn't work.

dictionary[0]
dictionary.zero {"number"=>"0"}
dictionary["one"] {"number"=>"1", "adj"=>["first", "unary"], "ordinal"=>"primary"}
dictionary.two.adj[0] second
dictionary["two"]["adj"][1] dual
dictionary["two"].adj[2] binary

Post a New Comment






?

Note: for security reasons, a mailto link is being used. If configured on your end, this is the safest way for both parties. This activates your mailer to send the data entered. See here or here for why that might not work and what to do about it.