Drupal 用于检查登录用户在tpl文件中同时具有两个角色的代码?
我想在一个页面--node--17.tpl.php中打印一段代码,以检查登录用户的角色,然后确定应该显示什么,因此基本上用户必须同时拥有角色a和角色C,如果他们拥有,我将打印xxx 如果他们有角色A和B,我写yyy 如果他们有角色B和C,我打印zzz 下面的代码可以检查一个角色,但如何同时检查这两个角色。。重要的是,两个角色都必须存在,只有其中一个角色的用户将不符合条件 谢谢你Drupal 用于检查登录用户在tpl文件中同时具有两个角色的代码?,drupal,drupal-7,drupal-modules,roles,Drupal,Drupal 7,Drupal Modules,Roles,我想在一个页面--node--17.tpl.php中打印一段代码,以检查登录用户的角色,然后确定应该显示什么,因此基本上用户必须同时拥有角色a和角色C,如果他们拥有,我将打印xxx 如果他们有角色A和B,我写yyy 如果他们有角色B和C,我打印zzz 下面的代码可以检查一个角色,但如何同时检查这两个角色。。重要的是,两个角色都必须存在,只有其中一个角色的用户将不符合条件 谢谢你 <?php global $user; // Check to see if $user has the
<?php
global $user;
// Check to see if $user has the administrator user role.
if (in_array('administrator', array_values($user->roles))) {
// Do something.
}
?>
我也有这段代码,但我认为这只是检查其中一个角色,所以它检查A或B
<?php
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
if (empty($check) ? FALSE : TRUE) {
// is admin
} else {
// is not admin
}
?>
创建一个可重用函数
<?php
function _mytheme_check_for_all_roles_present($roles) {
global $user;
foreach($roles as $key => $role) {
if (in_array($role, array_values($user->roles))) {
unset($roles[$key]);
}
}
return empty($roles);
}
要检查两个条件是否为真,需要AND(&&)运算符
在你的例子中,我会这样做:
<?php
//Load the current user
global $user;
// Check to see if $user has the A, B or C user role.
$as_A_role = in_array('A', array_values($user->roles));
$as_B_role = in_array('B', array_values($user->roles));
$as_C_role = in_array('C', array_values($user->roles));
?>
<?php if ($as_A_role && $as_B_role): ?>
// Do something.
<?php elseif ($as_A_role && $as_C_role): ?>
// Do something else
<?php endif; ?>
//做点什么。
//做点别的
<?php
if(_mytheme_check_for_all_roles_present(array('role_1_to_be_checked', 'role_2_to_be_checked')) {
echo "the thing you want to show";
}
<?php
//Load the current user
global $user;
// Check to see if $user has the A, B or C user role.
$as_A_role = in_array('A', array_values($user->roles));
$as_B_role = in_array('B', array_values($user->roles));
$as_C_role = in_array('C', array_values($user->roles));
?>
<?php if ($as_A_role && $as_B_role): ?>
// Do something.
<?php elseif ($as_A_role && $as_C_role): ?>
// Do something else
<?php endif; ?>