Liquid: Can I get a random element from an Array?

后端 未结 6 938
甜味超标
甜味超标 2021-02-13 10:49

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 \

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 11:29

    Without using a plugin (which might be a requirement if you are using github pages for example) and don't want the choice to be set only at build/rebuild time.

    This uses collections as it's data source and some feature flags set in the page front matter.

    {% if page.announcements %}
        
    {% endif %}
    

    I use markdownify to process the content, jsonify to make it JavaScript safe and then append a comma to make my array.

    The Javascript then populates one randomly at page load.

    Add collection to config.yml

    collections:
       announcements:
    

    Add flag to page

    ---
    layout: home
    title: 
    slider: true
    announcements: true    
    ---
    

    collection content item (test.md)

    ---    
    published: true
    ---
    
    This is a test post
    

提交回复
热议问题