Check for role in node-type.tpl.php
Is there any way to che开发者_StackOverflowck the role of the viewer within a drupal theme file, so as to write a conditional statement?
Thanks...
The current user is always available as a global variable, so just do:
// Make the user object available
global $user;
// Grab the user roles
$roles = $user->roles;
$user->roles will be an array of role names, keyed by role id (rid).
Edit: To be precise, the global user object is made available during early bootstrapping, in phase DRUPAL_BOOTSTRAP_SESSION
, but from the point of custom coding within themes or modules, you can treat that global as always available.
This will do
global $user;
$num_roles = db_fetch_object(pager_query(db_rewrite_sql('SELECT rid from {role} ORDER BY rid Desc')))->rid; // Find how many roles are there
for($i=0; $i < $num_roles; $i++){
if(strlen($user->roles[$i]) >0){
echo $user->roles[$i];
$i = $num_roles;
}
}
Just an appendix to Henrik Opel's answer: if you use it in a tpl.php file, then create a variable first in a preprocess_node function:
<?php
function YOURTEMPLATE_preprocess_node(&$variables) {
global $user;
$variables['current_user_roles'] = $user->roles;
}
?>
Now you can print your roles in your tpl.php:
<?php
if ($current_user_roles) {
?>
<ul class="roles">
<?php
foreach ($current_user_roles as $role) {
?><li class="roles-item"><?php print $role; ?></li><?php
}
?>
</ul>
精彩评论