Pier-Luc Bonneville
Pier-Luc Bonneville
Creator of this blog.
Mar 14, 2021 2 min read

Displaying HTML with values from variables in the dotnet kernel

thumbnail for this post
Photo by Florian Olivo

There are a few ways to get your interactive notebooks to write HTML to the client.

  1. Using the #!html and #!js magic commands.
  2. Using the PocketView API.
  3. Using the HtmlContentBuilder class.

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.

using the HTML and JS kernels

#!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.

using the PocketView API - example 1

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.

using the PocketView API - example 2

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.

using the PocketView API - example 3

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.Html namespace.

using the HtmlContentBuilder class

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.

References

  1. Displaying output in a notebook (C#)
  2. The PocketView API
  3. HtmlContentBuilder Class