using System; using System.Collections.Generic; using System.IO; namespace Mustache { /// /// Builds text by combining the output of other generators. /// internal sealed class CompoundGenerator : IGenerator { private readonly TagDefinition _definition; private readonly ArgumentCollection _arguments; private readonly List _primaryGenerators = new List(); private IGenerator _subGenerator; /// /// Initializes a new instance of a CompoundGenerator. /// /// The tag that the text is being generated for. /// The arguments that were passed to the tag. public CompoundGenerator(TagDefinition definition, ArgumentCollection arguments) { _definition = definition; _arguments = arguments; } /// /// Adds the given generator. /// /// The generator to add. public void AddGenerator(IGenerator generator) { addGenerator(generator, false); } /// /// Adds the given generator, determining whether the generator should /// be part of the primary generators or added as an secondary generator. /// /// The tag that the generator is generating text for. /// The generator to add. public void AddGenerator(TagDefinition definition, IGenerator generator) { bool isSubGenerator = _definition.ShouldCreateSecondaryGroup(definition); addGenerator(generator, isSubGenerator); } private void addGenerator(IGenerator generator, bool isSubGenerator) { if (isSubGenerator) { _subGenerator = generator; } else { _primaryGenerators.Add(generator); } } void IGenerator.GetText(TextWriter writer, Scope keyScope, Scope contextScope, Action postProcessor) { Dictionary arguments = _arguments.GetArguments(keyScope, contextScope); IEnumerable contexts = _definition.GetChildContext(writer, keyScope, arguments, contextScope); List generators; if (_definition.ShouldGeneratePrimaryGroup(arguments)) { generators = _primaryGenerators; } else { generators = new List(); if (_subGenerator != null) { generators.Add(_subGenerator); } } foreach (NestedContext context in contexts) { foreach (IGenerator generator in generators) { generator.GetText(context.Writer ?? writer, context.KeyScope ?? keyScope, context.ContextScope, postProcessor); } if (context.WriterNeedsConsidated) { writer.Write(_definition.ConsolidateWriter(context.Writer ?? writer, arguments)); } } } } }