-
Notifications
You must be signed in to change notification settings - Fork 2
Data files
Data files allow you to store data in YAML files, and reuse it across your project.
You can register directories containing data files directly from your config.rb file:
register_data_dirs(['data'])This registers all YAML files in the data/ directory, and makes them available via a method in your pages and layouts. This method is the name of the last directory in the path, in this case, data. In the case of the path path/to/other/folder, the method name would be folder.
You can customize the method name by passing a hash to the register_data_dirs method instead of an array, where the key will be the method name, and the value the directory to use.
register_data_dirs({
my_data_dir: 'path/to/data'
})The files in the registered directory are the methods that hold the data. This method of accessing data also works for sub-directories.
Consider the following directory structure:
data/
├── people.yml
└── departments/
├── sales.yml
└── engineering.yml
After you register your data/ directory, you can access all its data via the data method. Let's assume your people.yml file has the following content:
- Idris
- Viola
- NaomiNow, in any of your templates, you can access these names:
<% data.people.each do |name| %>
<%= name %>
<% end %>This approach also works with sub-directories. For example, let's assume your departments/sales.yml file has the following content:
enterprise:
- Idris
mid-market:
- ViolaYou can list all departments and employees by accessing the data in the following way:
<% data.departments.sales.each do |segment, employees| %>
People working in the <%= segment %> segment: <%= employees.join(', ') %>.
<% end %>