Life Through a Lens – Extending and Modifying Glass Rendering Output

Have been asked a couple of times lately about ways to extend Glass Mapper given that in many cases it does not call the renderField pipeline. Glass Mapper is a mature and extensible API, so it in itself is not so tricky to customise.

Below are a couple of example snippets on how you can modify / extend rendering of html (note – this code compiles, I have not run it in a production solution).

MVC Extensions

For Glass MVC extensions, you can simply create your own extension method

namespace xxx
{
    public static class MyGlassExtensions
    {
        public static HtmlString RemoveSpaces<T>(this GlassHtmlMvc<T> glassMvc, T target, Expression<Func<T, object>> field, object parameters = null)
        {
            HtmlString original = glassMvc.Editable(target, field, parameters);
            string result = original.ToString().Replace(" ", String.Empty);
            return new HtmlString(result);
        }
    }
}

This allows you in your view cshtml to call:

@Html.Glass().RemoveSpaces(Model, x => x.Title)

If you note, the glassMvc Editable() method is called, this is due to the fact at present that GlassHtml is not available to the extended method, I have submitted a change for consideration to allow this to be available.

Inherited GlassView

namespace xxx
{
    public abstract class MyGlassView<TModel> : GlassView<TModel> where TModel : class
    {
        public HtmlString RemoveSpaces(TModel target, Expression<Func<TModel, object>> field, object parameters = null)
        {
            string original = GlassHtml.Editable(target, field, parameters);
            string result = original.Replace(" ", String.Empty);
            return new HtmlString(result);
        }
    }
}

Providing in your view cshtml file you inherit from MyGlassView, then this allows you to call the following:

@RemoveSpaces(Model, x => x.Title)

Hope this helps 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s