How are templates executed?

From Joomla! Documentation

Templates are executed in a 2-phase process that makes full use of the PHP parser to provide considerable flexibility and performance to the template designer. Templates are executed in the context of the document object so that the $this object is always the instantiation of the JDocument class.

Before template execution begins, the component will have been executed and its output buffered for later use.

Template execution then proceeds as follows:-

template parameters (if any) are loaded.

template language (if any) is loaded.

if legacy mode is on then the configuration variables are copied as globals.

the template file (index.php) is loaded and executed (by PHP). The output is buffered. This is phase 1 of the 2-phase process. Everything between <?php and ?> tags is executed as PHP code. Everything outside of these tags is output but otherwise ignored. As the output is being buffered, nothing is sent to the client web browser at this stage.

a favicon.ico file is looked for, first in the Joomla! root directory, then in the template root directory. The latter will override the former if found.

the output that was buffered in phase 1 is now parsed for <jdoc:include> elements. This is phase 2 of the process. For each jdoc element found, the appropriate renderer class is loaded and its render method is called. The output from the render method replaces the <jdoc:include> element itself in the output buffer. In the case of module renderer classes this triggers the execution of the modules and the buffering of their output.

Certain template-specific HTTP headers are added to the list of headers to be output.

Control is then passed back to the JApplication object which will handle the rest of the process of getting the now rendered web page back to the client web browser.