Jump to content

Theme Tip: Use HTML logic to display content to specific groups

HTML Logic is our name for the additional tags available in IPS4's templates that allow runtime logic to be executed. It comprises if/then/else statements as well as loops and more.

Since HTML Logic has access to all of the underlying PHP framework in IPS4, it's very powerful and a lot can be achieved with it. One common use is to limit certain content within a template to particular member groups. Let's see how that might be done.


Showing or hiding content only to guests

We'll first look at a simpler idea: showing or hiding content specifically to guests (i.e. anyone who isn't logged in). Within IPS4, the \IPS\Member::loggedIn() object contains information about the current user. Guests always have a member_id of NULL (i.e. no value), so we can simply check that value in our logic tag:

{{if \IPS\Member::loggedIn()->member_id === NULL}}
	This content *only* shows to guests, since they have a NULL member_id.

{{if \IPS\Member::loggedIn()->member_id}}
	This content *only* shows to logged-in users since their member_id is a number, which will equal true.


Showing content only to specific groups

Let's go a bit further and this time show content to specific (primary) member groups. First, you need to get the IDs for the group(s) you want to deal with. You can find this by editing the group in the AdminCP, and making a note of the id parameter in the URL. On my installation, the Administrator group is ID 4 so we'll use that in our example.

Once again, we're using the \IPS\Member::loggedIn() object, but this time we're using the member_group_id property.

{{if \IPS\Member::loggedIn()->member_group_id === 4}}
	This content only shows to members in the "Administrators" group (ID 4 in our example)


Working with multiple groups at once

Following the code above, you could simply repeat the check against \IPS\Member::loggedIn()->member_group_id several times, for each ID you want to allow. However, since our templates allow arbitrary PHP expressions to be used, there's a neater way: use an array of member group IDs you want to allow, and check against that using PHP's in_array function. Here's an example where we only show content to group IDs 2, 4 and 6:

{{if in_array( \IPS\Member::loggedIn()->member_group_id, array( 2, 4, 6 ) )}}
	This content only shows to members in groups with the ID 2, 4 or 6.


Have a request for a theme tip? Let us know in the comments and we'll try and help out in a future tip! 

  • Create New...