Using wp_localize_script inside template page to transfer var from php to js

I finally solved it ! 🙂

The problem was that I add my function to localize and enqueue my script at the end of the page with the function itself, after wordpress loop. So I finally add the function before to get the header and this time, I can pass variables normally.

(I already register my script in function.php)

Code before (wrong) :

[...Code...]
function pass_var_to_js() {
    global $my_variable;
    wp_localize_script('script_name','send_var', array( $my_variable ) );
    wp_enqueue_script('script_name');
}
add_action('wp_enqueue_scripts', 'pass_var_to_js');

Code after (right) :

[...Code...]
add_action('wp_enqueue_scripts', 'pass_var_to_js');
get_header();
[...Code...]
function pass_var_to_js() {
    global $my_variable;
    wp_localize_script('script_name','send_var', array( $my_variable ) );
    wp_enqueue_script('script_name');
}

I hope that it could help someone !