Skip to content

Instantly share code, notes, and snippets.

@jsommr
Last active April 26, 2016 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsommr/a1e472f488dab9c6b78e23d818e82630 to your computer and use it in GitHub Desktop.
Save jsommr/a1e472f488dab9c6b78e23d818e82630 to your computer and use it in GitHub Desktop.
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