Asp.Net Core Custom tag helper for gravatar image from Email
As we have excellent documentation on the official documentation page explaining in detail what tag helpers are and what problem they solve, i am not going to repeat that here.This is going to be mostly code :)
While rewriting TeamBins, the open source issue tracking software from ASP.NET MVC5 to Asp.Net core, I decided to convert an exisitng gravatar html helper to a tag helper. Here it goes.
This tag helper can be invoked on any span elements. Email attribute name (
gravatar-email) is the only required field. This can be called in another view like this
<span gravatar-email="YourValidEmailAddressHere" image-size="26"></span>
When razor executes this view code, it will render the below html markup
<span><img src="http://www.gravatar.com/avatar.php?gravatar_id=YourEmailHash?s=26" alt=""></span>
YourEmailHash will be replaced with the hash generated from the email address.
If email is a property of your view model you will use that property as the value of
<span gravatar-email="@Model.EmailAddress" image-size="26"></span>
You also need to add an
addTagHelper directive call in your
_ViewImports.cshtml file for the tag helper to work. The second argument is the assembly name where your tag helper is defined. In my case, It is in my
TeamBinsCore.Web project (and assembly)
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, TeamBinsCore.Web