I want to use the $comment
object in page.tpl.php.
Is there a function or a way to use it?
1 Answer
The page.tpl.php template file is used for any page output from Drupal; it is not said the page is being output for a node. It would be rather better to use node.tpl.php, which is always used for a node, except when a different template is being suggested and that file exists.
The code I am reporting is valid for page.tpl.php, but with few changes it can be used also for node.tpl.php.
I am taking the assumption you are interested in the comments for the node being shown.
if (!empty($node)) {
$result = db_query('SELECT * FROM {comments} WHERE nid = %d', $node->nid);
while ($comment_obj = db_fetch_object($result)) {
// $comment_obj contains the comment object.
// ...
}
}
In the case the code is used in node.tpl.php, it is not necessary to verify if $node
is not empty, as the template is surely used to visualize a node.
I called the variable $comment_obj
because in node.tpl.php there is already a variable named $comment
, but that variable doesn't contain any comment object; it contains the comment settings for the node.
As pointed out from Jeremy French, such code should never go inside a template file, which should just contain presentation code (i.e. code that prints out the content of variables). That code could be the body of a function (contained in template.php of a theme) that builds up the output shown from the template file; alternatively, similar code should be used in a preprocess function.
In this case, the code is similar to the following one.
function mymodule_preprocess_node(&$variables) {
$variables['comment_output'] = '';
if (!empty($variables[node])) {
$result = db_query('SELECT * FROM {comments} WHERE nid = %d', $variables[node]->nid);
while ($comment_obj = db_fetch_object($result)) {
// $comment_obj contains the comment object.
// ...
$variables['comment_output'] .= // ...
}
}
}
page.tpl.php should then print the content of $variables['comment_output']
.
print $comment_output;
To notice also that Drupal uses comment.tpl.php, to which is passed a comment object. Depending on what you are trying to do, that could be the template file you are really interested in.
-
It is worth noting that the code snippet above should go in a preprocess hook not in the page.tpl.php Apr 12, 2011 at 12:37
-
All roads lead to Rome. love drupal! how to do it? could you give your answer? Apr 12, 2011 at 12:48
-
Jeremy French is right; I didn't want to make the answer more complicated, but the answer would not be correct if it would make others understand that is correct to put such code inside a template file. I expanded my answer.– apaderno ♦Apr 12, 2011 at 13:16
-