Quantcast
Channel: C1 CMS Foundation - Open Source on .NET
Viewing all articles
Browse latest Browse all 2540

New Post: Add class to body

$
0
0
There is no need to use MasterPages in this case.

The easiest way to add a class to the final page page body element (from a function) is to add that attribute class to the function output body element. Below Razor function is an example:
@inherits RazorFunction

@functions {
    public override string FunctionDescription
    {
        get  { return "Add a class name to the page body, if not already defined"; }
    }
     
    [FunctionParameter(Label = "Class name", Help = "Help text here...", DefaultValue = "classy")]
    public string Class { get; set; }
}

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    </head>
    <body class="@Class">
    </body>
</html>
C1 will 'pull up' all attributes you define on the body elements (provided they are not already defined - we will not overwrite or compound). Be aware: If another function also adds a class attribute or you have it in your template markup, only one will survive (the one that was added first). So this is brittle.

Other ways to dynamically manage the body element:

Make a C1 Function that has return type XAttribute and attach it as a child to your <body> open in your template. If C1 gets an XAttribute from a function it will stick it on the parent element.

Example C# Function code:
using System;
using System.Xml.Linq;

namespace Sample
{
    public static class InlineMethodFunction
    {
        public static XAttribute ClassAttribute()
        {
            return new XAttribute("csharp", "value");
        }
    }
}
A third way is kind of turn the template markup inside out - rather than having the template start with <html> you start it with <f:function > and this function wraps the html part. So your function will receive the entire page as input on a parameter of type XhtmlDocument - and you emit the final XhtmlDocument - in your function code you can punch things around as you please.

Example from a template where html is wrapped by a funtion call:
<!DOCTYPE html>
<f:function name="Composite.Web.BundlingAndMinification" xmlns:f="http://www.composite.net/ns/function/1.0">
    <f:param name="Page">
        <html xmlns="http://www.w3.org/1999/xhtml" class="no-js" lang="@Lang">
        <head>
            <title>@CurrentPageNode.Title</title>

            ...........
We use this strategy on the Venus Starter Site (go edit the MasterLayout.cshtml file).

Viewing all articles
Browse latest Browse all 2540

Trending Articles