Correct way to pass specific data to single template with Controller

I’m able to pass data no problem from Controllers/App.php but I’m assuming it’s a good practice to setup files for individual templates if only those templates need access to the data, rather than having only a bunch of global data. The only information I’ve found on this is that the file name in Controllers and the class need to line up with the blade template name, but how exactly? I’ve tried variations of using the same name as the page template file name and/or page template name, and I get an error.

My file is setup as follows. I’m just getting some custom fields here that I made with the ACF plugin. File in controllers is Controllers/front-page.php and blade template is front-page.blade.php. Controllers file uses class FrontPage...:

The code works perfectly fine when in Controllers/App.php. However, as setup currently I get the following error: Fatal error: Uncaught ReflectionException: Class App\Controllers\front-page does not exist in /app/public/wp-content/themes/red-egg/vendor/soberwp/controller/src/Loader.php:121 Stack trace: #0 /app/public/wp-content/themes/red-egg/vendor/soberwp/controller/src/Loader.php(121)

Is anyone able to clarify how this works, and if indeed I should be going about this the way that I am (separate controller files for specific data only needed by certain templates)? Any advice is appreciated. Thanks!

Hey @abgregs - your controller file name should match the way you formatted your class name: FrontPage.php. Basically, take the template name and capitalize each segment, then remove the dashes (e.g., taxonomy-mytaxonomy.blade.php -> TaxonomyMytaxonomy.php).

Well, that was easy :slightly_smiling_face:

I saw the lowercase dashed convention elsewhere and I guess hadn’t tried your answer yet. Awesome, thank you @mmirus ! Now I know.

Yeah, I think that was from an early version of Sage 9–maybe the beta, don’t remember for sure.

This topic was automatically closed after 42 days. New replies are no longer allowed.