by Ryan Irelan
How does Craft know which template to render when? It all starts and ends with Craft’s request routing.
The Craft documentation for Routing starts us off perfectly:
When a request comes in, Craft goes through several checks when determining where to route the request.
Craft does a routing check sequence that every request goes through so it ends up at the right place, delivering the right page or asset.
Pull up the routing documentation page and let’s talk through it.
The first three checks in the routing sequence:
cover whether Craft should take the request at all (sometimes it’s not necessary), if it’s a request for a Craft-managed resource, or if it’s an action request (like submitting a form or other actions from third-party plugins).
The fourth check is if the request is for an entry or category page. If there is a URI match then Craft will load the proper template (the one you specified when setting up the category or section).
The fifth check is if the request matches any Dynamic Routes you set up in the Craft control panel. Dynamic routes are hugely powerful in allowing you to create custom URIs that don’t necessarily match the template path. This saves you from having to conceive an unusual template directory and file naming scheme just to get the URLs to be how you want. If there is a match then Craft will render the template specified in the matching Dynamic Route.
The second-to-last check in the sequence to see if the request URI matches a template. If the URI is a valid template path (directory + template), then Craft will render that template.
This is a literal routing of the URI to the template.
If you have a request for
offices/austin.html and Craft goes through its checks and doesn’t find a match before it gets to the template check then it will render the
offices/austin.html template. If you had an entry with that URI then it would render the entry instead (using whichever section entry template you specified).
At the end of the check sequence, if there are no matches, Craft will return a 404 error. If you don’t have a custom 404 template, Craft will render the default view. To create a custom 404 template, add a
404.html template file in the root of your
craft/templates directory and Craft will use it.
My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.