Skip to content

Instantly share code, notes, and snippets.

@thamas
Last active April 16, 2019 21:41
Show Gist options
  • Save thamas/5a7d34ea10e365ec4fb519220d101f97 to your computer and use it in GitHub Desktop.
Save thamas/5a7d34ea10e365ec4fb519220d101f97 to your computer and use it in GitHub Desktop.
Usage of Twig random() in Pattern Lab to provide more dynamic test content

willthemoor [1:17 AM] .
Just coming to realize the power of flat arrays within _data/data.json and the use of twig's random() function for mocking stuff in Pattern Lab. It's good living!

data.json

"schools" : [
  "Georgetown",
  "Harvard",
  "Princeton",
  "Yale"
],
"years" : [
 "1996",
 "2001",
 "2006",
 "2011"
]

foo.twig:

<li>Education: {{ random(schools) }}, {{ random(years) }}</li>

willthemoor [9:13 PM] .
random() is also handy for testing design resilience (etc) by 'conditionally' including data points. I should maybe note that I'm working on 'listing' type UI with many listings, each with many different potential data points (displayed directly in the listings).

{% if random(1) %}
  // render some data point
{% endif %}

I went a step further because the listings are user generated and almost nothing is required so each data point is very hit and miss. Since some data points are a more commonly filled than others I added the following to _data/data.json:

"binary_lean_true":  [0,0,1,1,1,1,1],
"binary_lean_false": [0,0,0,0,0,1,1],

Which allows for "probably" and "probably not" tests with {% if random(binary_lean_true) %} and {% if random(binary_lean_false) %}

Hmm... now that I've typed this out it occurs to me that it might also be possible to skip the probably/probably-not checks simply by adding blank entries to each flat array in data.json. Though I might hate myself a year from now when I'm wondering "wtf is with all of these empty array items??"

Bonus random() round because, dang, twig is friendly/forgiving 🙌:skin-tone-4: ! Want to test variable amounts of several data points without doing it manually? Say an entity is allowed between 0 and 5 school associations:

{% for i in 0..random(5) %}
  {{ random(schools) }}
{% endfor %}

Possibly worth noting: PL hangs on to these 'random' values when refreshing the page manually (at least with Emulsify's PL settings) since it only re-renders the HTML when there's an actual change to a file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment