Passing variables to get_template_part

Hi guys it's been a while since my last post and I feel sad that I was not able to contribute on web. Anyway I hope with this simple trick I'll share, I'll be able to help some of my fellow developer.

The goal of this tutorial is know how to pass your variable inside the template being called by the get_template_parts function of wordpress without defining it as glogal.

I'm still unsure if it's the best way for wordpress though but to me it feels right.

Here it is

Instead of 

global $test;

$test = "hello world!";

get_template_part('templates/world','hello');

 

and fetching it from the template

[root]/wp-content/themes/[yourtheme]/templates/world-hello.php

global $test;

echo $test;

 

Do it this way using wordpress' function set_query_var and get_query_var

set_query_var('test','hello word');

get_template_part('templates/world','hello');

 

and fetch it from the template

[root]/wp-content/themes/[yourtheme]/templates/world-hello.php

echo get_query_var('test');

 

That's it! I would be happy to hear your opinion regarding on this method.