Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.Linq;
using Nustache.Core;
static ILookup<string, string> GetMetadata(string templateContent) {
// All metadata are written as {{! key: value }}. {{! ... }} is a comment in Mustache.
// This function uses the possibility to alter start and end delimiters to scan for {{! }}
// instead of {{ }}. With {{! as start delimiter, {{!! becomes a comment. I don't think
// you need comments in this case, but I think this is a neat way to include metadata in
// the templates.
return new Scanner("{{!", "}}")
.Scan (templateContent)
.OfType<VariableReference> ()
.Select (varRef => varRef.Path.Split(':'))
.Where (x => x.Length == 2)
.ToLookup(x => x[0].Trim(), x => x[1].Trim());
}
/*
Usage
=====
template:
{{! from: admin@mywebsite.org }}
{{! subject: Regarding your browser history }}
<body>
<h1>Dear {{ name }}</h1>
<p>.....</p>
</body>
*/
var tmpl = "{{! from: admin@mywebsite.org }}\n {{! subject: Regarding your browser history }}\n <body>\n <h1>Dear {{ name }}</h1>\n <p>.....</p>\n </body>";
var metadata = GetMetadata (tmpl);
var body = Render.StringToString (templateContent, new { name = "John Doe" });
var from = metadata["from"].FirstOrDefault();
var to = "johndoe@mywebsite.org";
var subject = metadata["subject"].FirstOrDefault();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment