Move menu code to the template.php with the associate hook I have created a region (called menuCustom) .info file in my template, I created a custom menu and I'm showing in the previously created region.

I created a file called block--menuCustom.tpl.php to show it as a block.

My question:
How I can move code from the .tpl file to the file template.php?

I have managed to show the links with the structure needed with the following code:

&lt;?php
    $contenidoDesple = $elements['#content'];

    $templateMenu = '&lt;ul class="' . 'desple"&gt;';

    foreach ($contenidoDesple as $key =&gt; $item) {

        if ($key != '#sorted' &amp;&amp; $key != '#theme_wrappers') {

            $enlace = $contenidoDesple[$key]['#href'];
            $nombreEnlace = $contenidoDesple[$key]['#title'];

            $templateMenu .= '&lt;li class="' . 'item"&gt;';
            $templateMenu .= '&lt;a class="' . 'link-k" href="' . $enlace . '"&gt;' . $nombreEnlace . '&lt;/a&gt;';

            if (count($contenidoDesple[$key]['#below']) != 0) {

                $templateMenu .= '&lt;ul class="' . 'sub-menu"&gt;';

                foreach ($contenidoDesple[$key]['#below'] as $newKey =&gt; $newItem) {

                    if ($newKey != '#sorted' &amp;&amp; $newKey != '#theme_wrappers') {
                        $enlace2 = $contenidoDesple[$key]['#below'][$newKey]['#href'];
                        $nombreEnlace2 = $contenidoDesple[$key]['#below'][$newKey]['#title'];

                        $templateMenu .= '&lt;li class="' . 'item"&gt;';
                        $templateMenu .= '&lt;a class="' . 'link-k" href="' . $enlace2 . '"&gt;' . $nombreEnlace2 . '&lt;/a&gt;&lt;/li&gt;';
                }
            }

            $templateMenu .= "&lt;/ul&gt;";

        }

        $templateMenu .= "&lt;/li&gt;";

    }

}
$templateMenu .= "&lt;/ul&gt;";

print $templateMenu;

?&gt;
You can add your code to custom module as custom block:

/**
 * Implements hook_block_info().
 */
function custom_block_block_info() {
  $blocks = array();
  $blocks['my_block'] = array(
    'info' =&gt; t('My Custom Block'),
  );      
  return $blocks;
}
/**
 * Implements hook_block_view().
 */
function custom_block_block_view($delta = '') {
  $block = array();      
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }      
  return $block;
}

/**
 * Custom function to assemble renderable array for block content.
 */
function my_block_view() {
  $output = '';
  $menu_array = menu_tree_all_data('main-menu');
  // Prepare your $output variable from $menu_array (like in your code).    
  $block = array(
    'menu' =&gt; array(
      '#type' =&gt; 'markup',
      '#markup' =&gt; $output,
    )
  );    
  return $block;
}


Then show this block in created region.