Content templates in an ASP.NET Core rich text editor

Announcements, meeting notes and product pages all have a shape. Templates let people start from your layout rather than an empty page, and they keep content consistent. In RichTextBox you build the list in C#.
Add the button and the list
The button's name is inserttemplate, and it is in the default and full toolbars. Pass the list as JSON:
@using System.Text.Json
@{
var templates = JsonSerializer.Serialize(new[]
{
new { name = "Announcement", html = "<h2>Announcement</h2><p>What is happening, and when.</p>" },
new { name = "Meeting notes", html = "<h2>Meeting notes</h2><ul><li>Decisions</li><li>Actions</li></ul>" },
});
}
<richtextbox name="Body"
toolbar="default"
height="400px"
html-templates-json="@templates"></richtextbox>
Templates from your database
Since the list is built on the server, it can come from anywhere, and it can depend on the user:
public class EditModel : PageModel
{
public string TemplatesJson { get; private set; } = "[]";
public async Task OnGetAsync([FromServices] AppDbContext db)
{
var rows = await db.Templates
.Where(t => t.Team == User.FindFirstValue("team"))
.Select(t => new { name = t.Title, html = t.Html })
.ToListAsync();
TemplatesJson = JsonSerializer.Serialize(rows);
}
}
The dynamic templates demo and the categories demo show more ways to organize them.
Keep template HTML simple
- Use headings, paragraphs, lists and tables. They survive editing and cleaning.
- Avoid inline scripts and style blocks, which the cleaner removes when the document is saved.
- Style through your site's stylesheet. Give the page a content stylesheet with
content-css-url, so the template looks the same in the editor as on the published page.