Signup for our Newsletter!

Signup below to receive all of Biznet's tips and newsletters delivered right to your inbox!

Kentico CMS: Conditionally Handling Visibility of Web Parts using K#

Kentico CMS: Conditionally Handling Visibility of Web Parts using K#

Biznet is a Kentico Gold PartnerA common task that arises in what seems to be each Kentico project I work on is the need to include a specific web part on either a solitary page or a specific instance of a page. There are, or course, many different ways to handle this issue. Creating a new page template for just one page works, but that’s one more page template to keep track of. Editing the source code of the web part is also a possibility, but might be considered overkill for the simplicity of the task. One of the easiest solutions I’ve come across is to customize the “Visible” setting on the web part using K#.

Kentico CMS: Web Part Properties

By default, the “Visible” setting is presented as a check box, returning a Boolean value. By clicking on the right arrow icon (See above image), you can open the “Edit value” dialog box, allowing you to create a macro that returns a Boolean value in lieu of the default check box. Clicking the “Remove macro value” button will revert the setting back to a check box (See image below).

Kentico CMS: Edit Value Dialog Box

Examples

{% if ( QueryString["Foo"] == "Bar" ) { return true; } else { return false; } #%}

The above code will return true if the query string with the key of “Foo” is set to “Bar”. Very handy if you need to show/hide a web part based on a query string parameter!

{% if ( CurrentPageInfo.DocumentName == "Foo Bar" ) { return true; } else { return false; } #%}

The above code will return true if the current document name is “Foo Bar”. Very handy if you need to show/hide a web part on a specific page!

Kentico CMS: Edit Value Dialog Box: Macro Object Tree

You have access to a plethora of Kentico objects. You can see a list of these objects when you click the “Show / hide macro object tree” button to the left of the blue “Insert” button (See image above). The possibilities are endless!

  • Mike

    Cant get my example to work when trying to hide a webpart from anyone in a role called trade…

    {%if (CurrentUser.IsInRole(“trade”)) {return false; } else { return true; }#%}

  • Steve Sanchez

    Hmm, that should work, although you could could just use {%(!CurrentUser.IsInRole(“trade”))#%}

    You can also try putting that macro in the html before/after area of the part – that will let you see exactly how it is resolving (then cut and paste into the visibility section). That way you can quickly make sure the role check is working right.