I was playing around a little tonight and was able to return data to my page template. I’d love some feedback on this if anyone has time.
Okay, so I have 2 pages, titled “post-1” and post-2", and both pages are using a custom page template. In this case I’m using the default custom page template that ships with Sage, and I’ve made a partial called content-page-custom.blade.php
I also have a file I’ve added to /src/
called controllers.php, in which I have the follwing -
namespace App;
function post1()
{
$data = [
'title' => 'List',
'names' => [
'Frank',
'Bob',
'Mary'
]
];
return $data;
}
add_filter( 'sage/template/post-1/data', 'App\\post1' );
function post2()
{
$data = [
'title' => 'List 2',
'names' => [
'Bill',
'Sally',
'Becky'
]
];
return $data;
}
add_filter( 'sage/template/post-2/data', 'App\\post2' );
function both()
{
$data = ['both' => 'Both'];
// Undefined, gets overwritten
return $data;
}
add_filter( 'sage/template/page-template-template-custom-blade/data', 'App\\both' );
Then, on my partial I have -
<h2>{{ $title or 'Not Defined' }}</h2>
<ul>
@foreach($names as $name)
<li>{{$name}}</li>
@endforeach
</ul>
<h2>{{ $both or 'Not defined' }}</h2>
The lists output as expected, with post-1 getting the correct data back for the post-1 filter, and post 2 getting the correct data back as well.
The both()
function should return identical data to both pages, and is hooked into page-template-template-custom-blade
, but gets overwritten because it fires earlier and $data
it’s in the same scope as the lists.
So… questions…
Am I on the right track here?
What’s the best way to avoid having my variables overwritten, like in my both()
example?
It seems that whatever I save in the $data
variable has to be saved in key value pairs, right?
Any feedback would be most appreciated, I feel like I’m pretty close to understanding this.