Displaying HTML with values from variables in the dotnet kernel

There are a few ways to get your interactive notebooks to write HTML to the client.
- Using the
#!htmland#!jsmagic commands. - Using the
PocketViewAPI. - Using the
HtmlContentBuilderclass.
Here are a few examples of how to display HTML with values from variables in the dotnet kernel.
1) Using the HTML and JS kernels
In this first example we must create the variable and assign it a value in a C# notebook cell.
Then using a multi-language single notebook cell, we can write our HTML and JavaScript to retrieve the variable and then replace the innerHTML of the div tag.

#!csharp
var hi = "hello";
#!html
<div id="output"> </div>
#!js
(async () => {
let output = document.getElementById("output");
output.innerHTML = await interactive.csharp.getVariable("hi");
})();
2) Using the PocketView API
This second example, although simple, is using the PocketView API returning an IHtmlContent.

var hi = "hello";
b[style: "color: red"](hi)
As we can see, it can get complicated writing code using the PocketView API if you are not familiar with it.

var colors = new [] { "red", "green", "blue" };
ol(
colors.Select(x => li[style: $"color: {x}"](x))
)
Here is another example using the PocketView API with an a tag.

var colors = new [] { "red", "green", "blue" };
ol(
colors.Select(x => li[style: $"color: {x}"](
a[href: "https://en.wikipedia.org/wiki/" + x](x)))
)
For more information on how to use the PocketView API, please refer to the PocketView API documentaion on the dotnet interactive GitHub repository.
3) Using the HtmlContentBuilder class
The third way makes use of the HtmlContentBuilder class. The functionality closely resembles using a StringBuilder.
Notice that you have to import the
Microsoft.AspNetCore.Htmlnamespace.

using Microsoft.AspNetCore.Html;
var colors = new [] { "red", "green", "blue" };
var content = new HtmlContentBuilder();
content.AppendHtml("<ol>");
foreach(var color in colors)
{
content.AppendHtml($"<li style=\"color: {color}\">{color}</li>");
}
content.AppendHtml("</ol>");
content
Conclusion
Using the #!html and #!js magic commands, the PocketView API, and the HtmlContentBuilder class you have plenty of options for crafting and rendering HTML in all your .NET interactive notebooks.
What if there was another, more familiar way to mix HTML and C# code?
Check out my next post for how to achieve the same result using Razor markup.
