FluentTagBuilder for Sitecore 9 Dynamic Placeholders

      Comments Off on FluentTagBuilder for Sitecore 9 Dynamic Placeholders

A fluent wrapper for the TagBuilder class can make it much easier to work with the dynamic placeholders introduced in Sitecore 9.

For developers like me, one of the most exciting new features of Sitecore 9 is dynamic placeholders. This is a functionality that has been provided by the community for quite some time, but now it is finally a built-in feature of the product.

Happy Skelletor

Like the community implementations from which it was derived, Sitecore now provides a DynamicPlaceholder method on the Sitecore helper class.  However, the API that Sitecore provides in version 9 goes beyond any of the open source implementations that I have seen. One nice feature is that you can utilize a TagBuilder object to wrap your placeholders.

The DynamicPlaceholder method will accept either a TagBuilder or a Func<DynamicPlaceholderRenderContext, TagBuilder>. This is very helpful, but as you can see in the examples above, creating your TagBuilder is a little cumbersome. My first thought when seeing this was that it would be nice if TagBuilder had a fluent API. I certainly wasn’t the first person to have that thought. Here is amore complete implementation of a FluentTagBuilder class based on Matt Honecutt’s example:

And here are some extension methods that make it easier to use:

With these extensions, setting up your TagBuilder object is much more convenient: