Create a CurrentPage expression builder

The use of expression builders is a convenient way to bind content data to controls on a template. Let´s say that we want to create an expression used for initializing a web control with the current page´s property values with the expression syntax.

You can build your own expression by inherits the ExpressionBuilder class. The ExpressionBuilder class has one method that must be implemented, GetCodeExpression.

In this example, The "CurrentPage" expression prefix is used:

[ExpressionPrefix("CurrentPage")]
public class CurrentPageExpressionBuilder : ExpressionBuilder {
    public static object GetCurrentPageValue(string expression) {
        PageBase pageBase = HttpContext.Current.Handler as PageBase;
        return pageBase != null ? pageBase.CurrentPage[expression.Trim()] : null;
    }
    protected string ExpressionFormat {
        get { return @"Meridium.EPCms.Web.Compilation. CurrentPageExpressionBuilder.GetCurrentPageValue(""{0}"")"; }
    }
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
        return new CodeSnippetExpression(string.Format(ExpressionFormat, entry.Expression, entry.DeclaringType));
    }
}

To use the currentPage expression builder, you have to register it to the web.config in the section:

<configuration>
    <system.web>
        <compilation defaultLanguage="c#" debug="false">
            <expressionBuilders>
                <add expressionPrefix="CurrentPage" type="Meridium.EPCms.Web.Compilation. CurrentPageExpressionBuilder, Meridium.EPCms" />
            </expressionBuilders>
        </compilation>
    </system.web>
</configuration>   

With the expressionPrefix set to CurrentPage, the expression would look like this on a page template:

<%$ CurrentPage : MainBody %>

The type attribute of the add element is the type of the CurrentPage expression builder we have created. If you created the class file in \Code folder of your project, you only need to write the name of the class. But if you have created your own class library you have to enter the full name of the class and assembly where the class is located.

Now you can use your newly created CurrentPage expression provider like this:

<asp:Literal text="<%$ CurrentPage: MainBody %>" 
runat="server" />
  1. This is really cool! Wondered how much work it would take to implement something like this. Not much at all it seems. Thanks for showing it.

  2. Steve Celius:

    You're welcome!

Leave a comment

Use markdown syntax to add formating to your comment.

Enter ULS, but type the third character three times.