How can one use variables in a template or template part without polluting the global scope?

I feel there is a bit of confusion — let me try and clarify some key concepts.

A WordPress installation can potentially run huge amounts of 3rd party code. Code you can’t control. That leads to a high chance of naming collisions. That’s why WordPress coding standards suggest to “namespace” functions and variables declared in the global scope. If you’re defining a variable inside your functions or templates (so, not in the global scope), there is no need to “namespace” it.

Regarding templates in particular, you probably already know that you can pass data to templates you load through get_template_part() and the likes.

Data passed this way is in no way global: it’s only accessible to the template you’re passing it to. From the link I shared above:

In the above example, the additional data passed to get_template_part() through the $args variable can be accessed within the foo.php template through the locally scoped $args variable.

In other words, you don’t need to namespace your variables in your templates. This is perfectly fine:

 * This is a template file
 * @package my-theme

<h1><?php echo esc_html( $args['title'] ); ?></h1>
<h2><?php echo esc_html( $args['subtitle'] ); ?></h2>
<p>Hello world</p>