Correct way to render fields from query in tpl?
Personally, I would create an Entity View Mode for the content type with the fields arranged and formatted how I want them, then you can simply do:

$node = node_load($nid);
$node_view = node_view($node);
print drupal_render($node_view);


In your case, you need multiple nodes, so:

$views = node_view_multiple($nids, "name of entity view mode");
print drupal_render($views);


Now that you are using an entity view mode, you can give the markup you want in the node--node_type--view_mode.tpl.php file, and it will use that.

As for the query and dynamic code, it should go in a preprocess hook, and not the tpl itself. You can return it as a $variable to the template being rendered, usually this is a page callback.

Again, I don't know much about your module or where this code is. You could enable Entity View Modes and just shift this code and get rid of it, and leverage Views instead for the same exact result.