public (StringBuilder, StringReader) Execute( string currentLine, StringReader templateReader, StringBuilder output, IDictionary <string, object> model = null) { if (currentLine == null) { throw new ArgumentNullException(nameof(currentLine)); } var forEachDetails = Regex.Match(currentLine, @"@foreach\s*\((?'criteria'.*)\)"); if (!forEachDetails.Success) { throw new MalformedException($"Malformed foreach statement: `{ currentLine }`."); } var loopCriteria = forEachDetails.Groups["criteria"].Value.Trim(); if (!loopCriteria.StartsWith("var")) { throw new MalformedException("Missing keyword `var`"); } var variableRefs = Regex.Match(loopCriteria, @"var\s*(?'varName'[\w]+)\s*in\s*(?'collection'[\w.]+)"); if (!variableRefs.Success) { throw new MalformedException(loopCriteria); } var varName = variableRefs.Groups["varName"].Value; var collectionNavProps = variableRefs.Groups["collection"].Value; // resolve collection if (!(model.GetReference(collectionNavProps) is ICollection collection)) { throw new Exception($"`{ collectionNavProps }` isn't a valid collection"); } // look for the loop statements. var forBlock = BlockReader.ReadBlock(templateReader).ReadToEnd(); var engine = new RazorAlikeEngine(); foreach (var item in collection) { var iteratorModel = model.Clone(); iteratorModel.DefineVariable(varName, item); var iterationOutput = engine.Run(forBlock, iteratorModel); output.Append(iterationOutput.ToString()); } return(output, templateReader); }
private void EvaluateStatements( string statements, IDictionary <string, object> model, StringBuilder output) { var engine = new RazorAlikeEngine(); var result = engine.Run(statements, model); output.AppendLine(result); }
public (StringBuilder, StringReader) Execute( string currentLine, StringReader templateReader, StringBuilder output, IDictionary <string, object> model = null) { var blockBody = BlockReader.ReadBlock(new StringReader(currentLine)); var engine = new RazorAlikeEngine(); var resolved = engine.Run(blockBody.ReadToEnd(), model); output.AppendLine(resolved); return(output, templateReader); }
public void SimplePositiveCase() { var template = @" Hello @user.name! @if (@user.showId == true) { Your ID is: @user.id. } Mail addresses: @foreach(var email in user.Emails) { @email.Value } "; var model = new { user = new { name = "Joseph Climber", id = 12345, showId = true, Emails = new List <object>() { new { Value = "*****@*****.**" }, new { Value = "*****@*****.**" }, } } }; var engine = new RazorAlikeEngine(); var result = engine.Run(template, model); Assert.AreEqual( @" Hello Joseph Climber! Your ID is: 12345. Mail addresses: [email protected] [email protected]", result); }