I am looking for help with DasBlog, lots and lots of help, and to that end I am trying to ensure that I am not just hacking at the code solo but providing an appropriate on ramp for new developers and/or first timers to open source. So I wanted to use the concept of TagHelpers to get folks productive quickly.

TagHelpers enable server-side code to participate in creating and rendering HTML elements in Razor files. They are developed using C# and enable custom HTML elements based on a simple naming convention, for example, if I were to create a “PostCreatedTagHelper” class it could activate it inside a page by using the tag. A really comprehensive introduction to TagHelpers can be found here, however, the following may be enough for you to start contributing.

TagHelpers in DasBlog

For people who are still using DasBlog I wanted the designing pages to be a simple task, especially if you are Web Designer by trade. I am planning on using TagHelpers to define components within the View (Title, Description, Category, etc) . If we take the case of a single post you will probably be getting information from the PostViewModel type and using it in the _PostPartial.cshtml page.

So imagine you are tasked with creating a new TagHelper that applies a date format to the PostViewModel.Created field, you would reference the TagHelper in the View as follows:

MMMM dd, yyyy

Setting post=@Model allows you to inject the Views model type directly into field of the TagHelper class you will need to create. The date format (MMMM dd, yyyy) becomes a useful input to the TagHelper class so that a designer can quickly change the format of the date output without knowing C#.

Here is an example where I create a HTML p tag, pull the format information from the View (as in "MMM dd, yyy") and apply it to the PostViewModel.Created date field:

public class PostCreatedTagHelper : TagHelper
{
    public PostViewModel Post { get; set; }

    public override async Process(TagHelperContext context, TagHelperOutput output)
    {
        var content = await output.GetChildContentAsync();
        string format = content.GetContent() 
        output.TagName = "p";
        output.Content.SetHtmlContent(Post.Created.ToString(format));
        output.TagMode = TagMode.StartTagAndEndTag;
    }
}

The final step is to ensure that your ViewImports.cshtml has a reference to the TagHelper class namespace and it should produce the following HTML:

June 10, 2017

This is a fairly straightforward case, and to be honest I probably would not be well served to use paragraphs in this context, but I hope this lays out an efficient way to start creating  your own TagHelpers over at DasBlog.

Please note that I have labeled these TagHelper tasks for code newbies who are looking to make contributions to supportive open source project using ASP.NET Core MVC. Please feel free to reach out to me on twitter and I will be happy to help walk you through this.



Comment Section

Comments are closed.