Skip to content

Instantly share code, notes, and snippets.

@thejhh
Created May 30, 2019 08:12
Show Gist options
  • Select an option

  • Save thejhh/4b7aacb52eddf2aad18dd7057590135e to your computer and use it in GitHub Desktop.

Select an option

Save thejhh/4b7aacb52eddf2aad18dd7057590135e to your computer and use it in GitHub Desktop.
Lodash's recursive `_.get(value, key)` functionality implemented in Liquid's include partial for Github Pages / Jekyll
{% comment %}
This works like Lodash's `_.get(value, key)`, where `value` can be an object and `key` a string path to specific value.
Use it like:
{% assign translation = site.data.lang[site.lang] %}
{% capture title %}{% include common/get-property.html value=translation key=page.title %}{% endcapture %}
And so, you can have your Front Matter title as "path.to.key" translated from your _data/lang/{fi,en}.json to correct value.
{% endcomment %}{%
if include.value and include.key %}{%
assign defaultValue = include.default | default: include.key %}{%
assign value = include.value %}{%
assign keys = include.key | split: "." %}{%
for key in keys %}{%
unless key %}X {{ defaultValue }}{% break %}{% endunless %}{%
assign value = value[key] %}{%
unless value %}Y {{ defaultValue }}{% break %}{% endunless %}{%
if forloop.last %}{{
value | default: defaultValue }}{%
endif %}{%
endfor %}{%
else %}No "value" or "key" property provided to get-property partial{%
endif
%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment