using System; using System.Collections.Generic; using HandlebarsDotNet; namespace MfGames.Nitride.Handlebars.Configuration; /// /// /// A typesafe model of the template. public class ForEachHandlebarsBlock : HandlebarsBlockBase { public ForEachHandlebarsBlock(string helperName) { this.HelperName = helperName; } /// /// Gets or sets the list that needs to be rendered. /// public Func>? GetList { get; set; } /// /// Gets or sets the callback that is called when nothing is found. /// public Action? NothingFound { get; set; } /// protected override string HelperName { get; } public ForEachHandlebarsBlock WithGetList(Func>? callback) { this.GetList = callback; return this; } public ForEachHandlebarsBlock WithNothingFoundText( Action? callback) { this.NothingFound = callback; return this; } /// /// Sets the output to write out text when no items are found. /// /// The text to write out. /// The same object for chained methods. public ForEachHandlebarsBlock WithNothingFoundText(string text) { this.NothingFound = ( output, _1, _2, _3) => output.Write(text); return this; } /// protected override void Render( EncodedTextWriter output, BlockHelperOptions options, Context context, Arguments input) { if (context.Value is not TModel model) { throw new InvalidOperationException( string.Format( "Cannot apply the {0} on context value because it is {1}.", nameof(ForEachHandlebarsBlock), context.Value.GetType())); } IEnumerable? list = this.GetList?.Invoke(model); bool hasItems = false; if (list != null) { foreach (object item in list) { hasItems = true; options.Template(output, item); } } if (!hasItems) { this.NothingFound?.Invoke(output, options, context, input); } } }