Last active
June 15, 2016 11:24
-
-
Save joeriks/e71131ec8d929ab86c8621bb40c0f71c to your computer and use it in GitHub Desktop.
Vanilla templating with string interpolation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private string TemplateTable(Dictionary<string, string> dict) | |
{ | |
var rowTemplate = new Func<string, string, string>((key, value) => $"<tr><td>{key}</td><td>{value}</td></tr>"); | |
return $"<table>{String.Join(Environment.NewLine, dict.Select(t => rowTemplate(t.Key, t.Value)))}</table>"; | |
} | |
private string PageTemplate(SomeModel model) | |
{ | |
var liTemplate = new Func<string, string, string>((key, value) => !string.IsNullOrEmpty(value) ? $"<li><strong>{key}</strong>{value}</li>" : ""); | |
return $@"<html> | |
<div> | |
<ul> | |
{liTemplate("Name", model.Name)} | |
{liTemplate("Address", model.Address)} | |
</ul> | |
</div> | |
<div> | |
{TemplateTable(model.Comments)} | |
</div> | |
</html>"; | |
} | |
// you can even use string interpolation within string interpolation: | |
private string PageTemplate(SomeModel model) | |
{ | |
var tag = new Func<string, string, string>((tagName, value) => $"<{tagName}>{value}</{tagName}>"); | |
var ul = new Func<string, string>(value => $"{tag("ul", value)}"); | |
var li = new Func<string, string, string>((key, value) => !string.IsNullOrEmpty(value) ? $"{tag("li", $"{tag("strong", key)}{value}")}" : ""); | |
return $@"<html> | |
<div> | |
{ ul($@" | |
{ li("Name", model.Name) } | |
{ li("Address", model.Address) } | |
") } | |
</div> | |
<div> | |
{TemplateTable(model.Comments)} | |
</div> | |
</html>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Another scenario where it looks like string interpolation could be useful –but isn’t– is templating. Templating is about building potentially large documents (usually HTML) with placeholders for expressions. It’s a complex problem, that involves tricky parsing, with lots of context changes, and strong requirements on encoding. String interpolation is simply not designed for that, even if the problem of requiring code-embedded literal strings wasn’t enough of a reason not to consider it. There are plenty of very good templating engines out there that you can use. Do that." Bertrand Le Roy http://weblogs.asp.net/bleroy/c-6-string-interpolation-is-not-a-templating-engine-and-it-s-not-the-new-string-format
However. If you prefer writing as much as possible in good ol' C# and you like to have awesome intellisense, everything compile time checked and no external dependencies you could consider using vanilla C# templating.