Move code from template file to custom module I would like to move portions of code from template files to custom module. But i fail do find descriptive guide for such task. Idea is to migrate complex db queries and EntitiyFieldQuery out of the tpl.php files. For example:

$query = new EntityFieldQuery();
$entities = $query-&gt;entityCondition('entity_type', 'node')
  -&gt;propertyCondition('type', 'predmet_clanak')
  -&gt;fieldCondition('field_taxonomy_choose', 'value', 1 , '=')
  -&gt;fieldCondition('field_vrsta', 'tid', 241);

$result = $query-&gt;execute();    
$nodes = entity_load('node', array_keys($result['node']));
foreach ($nodes as $node) {
  print ('&lt;div class="putujuci-wrapper"&gt;&lt;div class="putujuci"&gt;');    
  print drupal_render(node_view($node, 'teaser'));
  $nodelink = ltrim(url('node/' . $node-&gt;nid), "/");
  print ('&lt;/div&gt;');     

  $imageLink = '&lt;img src="' . $base_url . '/sites/all/themes/profil_edu/css/images/vise-button-static.png" width="55" height="28" border="0" class="img-swap"&gt;';
  print l($imageLink, $nodelink, array('query' =&gt; array('iframe' =&gt; 'true', 'width' =&gt; '800', 'height' =&gt; '700', 'format' =&gt; 'popup'), 'attributes' =&gt; array('class' =&gt; t('colorbox-load gumb')), 'html' =&gt; TRUE));
  print ('&lt;/div&gt;');     
}


This code fetches collection of nodes (when conditions are met) in custom tpl.php file. I have been advised not to create complex queries in tpl files, but do not know yet best practices to do so.

I guess, module will firstly need to know context where i want this to occur? And after i do  this in the module, do i need to pass this to the template.php first?
I think you should go through the module developer guide.

You can use hook_preprocess_HOOK() in your template.php. So if your code was placed in the node template, the hook will be themename_preprocess_node($vars) and then you can check for a particular node type and create a variable like $vars['custom_variable'] = 'the query stuff'; and this variable will be available in your template.