Last active
April 26, 2016 15:26
-
-
Save jsommr/a1e472f488dab9c6b78e23d818e82630 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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: [email protected] }} | |
{{! subject: Regarding your browser history }} | |
<body> | |
<h1>Dear {{ name }}</h1> | |
<p>.....</p> | |
</body> | |
*/ | |
var tmpl = "{{! from: [email protected] }}\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 = "[email protected]"; | |
var subject = metadata["subject"].FirstOrDefault(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment