Working with Moodle 3.9 and a fork of the current Academi theme.
I am trying to create a css classes on the <body>
element based on named user role(s). I understand that a user's role(s) are context-driven, (maybe a student in one course, and something else in another), so I would like to output all the roles as classes in a given context.
Based on some extensive digging on the forum I have the following:
// User role based CSS classes
global $USER, $PAGE;
$context = context_system::instance();
$roles = get_user_roles($context, $USER->id, true);
if(is_array($roles)) {
foreach($roles as $role) {
$PAGE->add_body_class('role-'.$role->shortname);
}
} else {
$PAGE->add_body_class('role-none');
}
Preferably I'd like this to run on every page. From within the theme, I've tried just placing this in just about every location/function I thought could be executed early enough to modify the body element. Either I get no output at all or a warning indicating that it is too late to run add_body_class().
I've had read of the docs on the Page and Output APIs, as well as the Themes overview and Roles/ Roles FAQ and I still don't have a sense of how to effectively fetch get_user_roles
and hook into add_body_class
.
I've also had a bit of difficulty as a lot of the search results on these topics, here on the moodle forum, and Sackoverflow are quite dated, so Im not sure what current best practice is.
Could someone give me a nudge in the right direction?