Search code examples
jekyll

Idiomatic way in Jekyll to inherit default data if project specific data unavailable


I am completely new to Jekyll. I did something like this:

  {% assign top_nav = site.data.menus %}
  {% if site.data.orgs[site.orgData].menus %}
    {% assign top_nav = site.data.orgs[site.orgData].menus %}
  {% endif %}
  <ul>
    {% for menu in top_nav %}
    <li>
      <a href="{{ menu.url }}">{{ menu.title }}</a>
    </li>
    {% endfor %}
  </ul>

Basically, I will grab an array of navigation items from a default folder. But if I notice the existence of a menu for a specific organization, then I will override the menu provided by the default folder.

What I don't like about this approach is I now have hundreds of places in my jekyll templates that does this if statement check. If this were any other scripting programming language, I would define a function like function($org_name,$prop) {return $site.data.orgs[$org_name][$prop] ? $site.data.orgs[$org_name][$prop] : $site.data[$prop]; } . What would be the idiomatic way to achieve the same objective in jekyll?


I tried a variation of David Jacquel's suggestion by doing this

./org_var.html

{% assign prop = include.prop %}

{% assign orgVar = site.data[prop] %}
{% if site.data.orgs[site.orgData][prop] %}
  {% assign orgVar = site.data.orgs[site.orgData][prop] %}
{% endif %}

./_include/nav.html

{% include_relative ../org_var.html prop=menus %}
{% for menu in orgVar %}
... print menu items

./_layout/header.html

{% include_relative ../org_var prop='electronics.televisions' %}
{% for tv in orgVar%}
{{ tv.modelName }}
... print tv values
{% endfor %}

But I get a syntax error in ../org_var.html saying {% include_relative file.ext param='value' param2='value' %} . The documentation says I can't use relative path with include or include_relative. How do I make my org_var.html a reusable and global function? And will electronics.televisions even evaluate properly to the proper path of my site.data.org.[site.orgData][...path] variable?


Solution

  • Just realized there is a default: modifier for a variable like smarty templates.

    {% assign top_nav = site.data.orgs[site.orgData].menus | default: site.data.menus %}