Collections

Variables & Helper Functions

Each collection can have its own set of variables and helper methods defined in the collection array in config.php. These follow the same format as the site-wide variables and helper methods that are defined at the top level of the config.php array.

Variables

Just as with site-wide variables, collection variables defined in config.php can act as defaults, which can be overridden by variables of the same name specified in the YAML front matter of a collection item. In fact, top-level variables in config.php will be overridden by variables of the same name in a collection's array, which will be further overridden by references in the YAML header of any individual page, allowing you to set up a cascade of variable defaults. For example:

config.php

1<?php
2 
3return [
4 'author' => 'Default Site Author',
5 'collections' => [
6 'posts' => [
7 'author' => 'Default Blog Author',
8 ],
9 ],
10];

_posts/blog-post-1.blade.php

1---
2extends: _layouts.post
3title: My First Post
4author: Keith Damiani
5---
6@section ('content')
7 
8<h1>{{ $page->title }}</h1>
9<p>By {{ $page->author }}</p>
10 
11@endsection

For this collection item, author will be Keith Damiani, the value from the YAML header.


_posts/blog-post-2.blade.php

1---
2extends: _layouts.post
3title: My Second Post
4---
5@section ('content')
6 
7<h1>{{ $page->title }}</h1>
8<p>By {{ $page->author }}</p>
9 
10@endsection

For this collection item, author will be Default Blog Author, the value from the posts array in config.php.

about-us.blade.php

1---
2extends: _layouts.about
3title: About our company
4---
5@section ('content')
6 
7<h1>{{ $page->title }}</h1>
8<p>By {{ $page->author }}</p>
9 
10@endsection

For this regular (non-collection) page, author will be Default Site Author, the value from the top level of config.php.

Helper Functions

Helper functions can be included in the collection settings array in config.php, and will be available to all of that collection's items. The same cascading rules that apply to variables also apply to functions, i.e. functions defined for a collection will override a function of the same name defined at the top level. For example:

config.php

1<?php
2 
3return [
4 'excerpt' => function ($page, $characters = 100) {
5 return substr($page->getContent(), 0, $characters);
6 },
7 'collections' => [
8 'posts' => [
9 'excerpt' => function ($page, $characters = 50) {
10 return substr(strip_tags($page->getContent()), 0, $characters);
11 },
12 ],
13 ],
14];