using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace mustache { /// /// Generates text by substituting an object's values for placeholders. /// public sealed class Generator { private readonly IGenerator _generator; private readonly List> _handlers; /// /// Initializes a new instance of a Generator. /// /// The text generator to wrap. internal Generator(IGenerator generator) { _generator = generator; _handlers = new List>(); } /// /// Occurs when a key/property is not found in the object graph. /// public event EventHandler KeyNotFound { add { _handlers.Add(value); } remove { _handlers.Remove(value); } } /// /// Gets the text that is generated for the given object. /// /// The object to generate the text with. /// The text generated for the given object. public string Render(object source) { return render(CultureInfo.CurrentCulture, source); } /// /// Gets the text that is generated for the given object. /// /// The format provider to use. /// The object to generate the text with. /// The text generated for the given object. public string Render(IFormatProvider provider, object source) { if (provider == null) { provider = CultureInfo.CurrentCulture; } return render(provider, source); } private string render(IFormatProvider provider, object source) { KeyScope scope = new KeyScope(source); foreach (EventHandler handler in _handlers) { scope.KeyNotFound += handler; } StringWriter writer = new StringWriter(provider); _generator.GetText(scope, writer); return writer.ToString(); } } }