In this episode, we dive into rendering views using Twig in our controllers. We start by hooking up our controller so that, instead of sending boring plain text, it takes advantage of our newly created home.twig
template. You'll see how to use a render
method (which we implement ourselves) to output the view, and how to pass data down to it.
We then walk through setting up the render
method on our View class, making sure Twig's environment is set up in the constructor, and using it as a little proxy so we can easily call Twig from anywhere in our app. Once that's done, we give our page a refresh and—boom—the Twig template is rendering our HTML.
After that's working, we show how easy it is to update the template, like putting a full HTML document in place, changing the title, and generally moving all the markup out of our controllers and into Twig files. We also cover the basics of passing data from our controller down into the template (like the app name), and how to get at that data in Twig using its syntax. If you're brand new to Twig, don't worry—we promise to walk through the basics as we go.
By the end, you've got a much tidier way to render your pages: one controller, one view, and a really clean hand-off of data between them. You'll be all set up to pass whatever info you want down to your views in the future!