Use page template name as a class in the ASCX Master Template

Mike Bilz asked on December 20, 2016 20:07

Hello Everyone,

For styling flexibility, I would like to have the template code name of the current page appear as a class in the master template. Something like this: <div id="mainContent" class="currentPageTemplate"><cms:CMSWebPartZone ZoneID="zoneContent" runat="server" /></div>

I found a macro that I think could get me the information I wanted: {% CMSContext.CurrentTemplate.CodeName %}

Unfortunately, after a few tries I learned that macros cannot be used inside of an ASCX template.

So, is the correct way to write something like this without using macros? Can it be done?

Thanks in advance.

Correct Answer

Brenden Kehren answered on December 20, 2016 20:30

If you want to set a specific class name to the body tag in a page template, you can do something like this and do it dynamically:

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
    Page.DataBind();
    CMS.DocumentEngine.DocumentContext.CurrentBodyClass += " your-class";
}
</script>

The class your-class can also come from a property on that particular page type like so

CMS.DocumentEngine.DocumentContext.CurrentBodyClass += CurrentDocument.GetValue("ColumnName", "");

0 votesVote for this answer Unmark Correct answer

Recent Answers


Anton Grekhovodov answered on December 21, 2016 09:19 (last edited on December 10, 2019 02:30)

Hi Mike,

You can add runat="server" attribute to your div. After that you can add css class for this UI element in code behind file of the template:

if (DocumentContext.CurrentTemplate != null) //it can be null
{
    mainContent.Attributes.Add("class", DocumentContext.CurrentTemplate.CodeName);
}

Also, you can resolve macros in C# code via MacroResolver class from CMS.MacroEngine namespace:

MacroResolver.Resolve("{% CMSContext.CurrentTemplate.CodeName |(identity)GlobalAdministrator%}")
1 votesVote for this answer Mark as a Correct answer

Mike Bilz answered on December 22, 2016 01:23

Thanks everyone!

I couldn't get Anton's suggestion to work on its own, but I was able to combine his code with Brenden's to get everything working how I wanted.

Here is my solution, if anyone else is looking to add this to their Master Template:

<script runat="server">
protected void Page_Load(object sender, EventArgs e){
    Page.DataBind();
    CMS.DocumentEngine.DocumentContext.CurrentBodyClass += CMS.DocumentEngine.DocumentContext.CurrentTemplate.CodeName;
}
</script>
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.