How to warm-up Twig?
The question sounds like coming from a Drupal 7 background :)

If I understand it correctly, you are looking for a way to execute some PHP logic before rendering the content. Just like what we were used to do in the *.tpl.php files.

However, PHPTemplate was removed and replaced by Twig for a reason. For truly separating business and presentation layers - on of the major reason.

This does not mean that you loose on to the control which you had with PHPTemplate files. This only means that you are now forced to follow the best standard practices ;-)

Ideally, in both Drupal 7 and 8 the template functions the rendering should be broken in two steps:


Business logic - The function which is responsible for initializing the data (to be returned to page). This could be a function which calls the theme() function, like the page callback of your hook_menu implementation where you pass the variables into it. These could also be the preprocess functions which could be used to add new and or change existing $variables to the theme element being called.
Presentation logic - These are nothing but the functions or template file responsible for printing the values that it gets from the Business layer into appropriate markup. In D7 we used *.tpl.php, whereas in D8 we use *.twig.


To deal with the issue at hand, you will need to the template_preprocess() function. The *.twig file is responsible to only print the variables, with minimum logical checks.