This content originally appeared on Hussein Al Hammad and was authored by Hussein Al Hammad
Statamic handles collection entries routing for you - given the route is set in the collection’s settings (can be done via the control panel or directly in the collection’s YAML file).
When Statamic routes to a collection entry page, it automatically includes the entry variables in the view. You can access the entry’s title directly through the variable title
. You don’t need to fetch the data in any way.
There are cases in which you need to create your own custom routes, and your own Laravel controllers that return Antlers views.
1public function index()2{3 return (new \Statamic\View\View)4 ->template('myview')5 ->layout('mylayout')6 ->with(['title' => 'Example Title']);7}
You can add the variables you want to be accessible to you within the antlers view by passing an array to the View::with()
method. But what do you do when you want to pass an entry’s variables to the view?
1use Statamic\Facades\Entry; 2 3public function index() 4{ 5 $my_entry = Entry::whereCollection('my_collection') 6 ->where('slug', $slug) 7 ->where('published', true) 8 ->first(); 9 10 return (new \Statamic\View\View)11 ->template('myview')12 ->layout('mylayout')13 ->with([14 // what do I add here?15 ]);16}
You can use the toArray()
method:
1<?php 2 3use Statamic\Facades\Entry; 4 5public function index() 6{ 7 $my_entry = Entry::whereCollection('my_collection') 8 ->where('slug', $slug) 9 ->where('published', true)10 ->first();11 12 return (new \Statamic\View\View)13 ->template('myview')14 ->layout('mylayout')15 ->with($my_entry->toArray());16}
And you can add other variables too:
1return (new \Statamic\View\View)2 ->template('myview')3 ->layout('mylayout')4 ->with(array_merge([5 // other variables6 ], $my_entry->toArray()));
However, you may run into unexpected templating issues with certain field types like the Entries fieldtype where can’t output the desired content even though you may be able to loop over the selected values for this field.
The better way to add your entry’s variables to the antlers view is by using the View::cascadeContent()
method:
1<?php 2 3use Statamic\Facades\Entry; 4 5public function index() 6{ 7 $my_entry = Entry::whereCollection('my_collection') 8 ->where('slug', $slug) 9 ->where('published', true)10 ->first();11 12 return (new \Statamic\View\View)13 ->template('myview')14 ->layout('mylayout')15 ->with([16 // some variables17 ])18 ->cascadeContent($my_entry);19}
This content originally appeared on Hussein Al Hammad and was authored by Hussein Al Hammad
Hussein Al Hammad | Sciencx (2024-01-06T00:00:00+00:00) Cascade Entry content into a routed Statamic Antlers view. Retrieved from https://www.scien.cx/2024/01/06/cascade-entry-content-into-a-routed-statamic-antlers-view/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.