This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride.Handlebars/Configuration/ForEachHandlebarsBlock.cs

96 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using HandlebarsDotNet;
namespace MfGames.Nitride.Handlebars.Configuration;
/// <summary>
/// </summary>
/// <typeparam name="TModel">A typesafe model of the template.</typeparam>
public class ForEachHandlebarsBlock<TModel> : HandlebarsBlockBase
{
public ForEachHandlebarsBlock(string helperName)
{
this.HelperName = helperName;
}
/// <summary>
/// Gets or sets the list that needs to be rendered.
/// </summary>
public Func<TModel, IEnumerable<object>>? GetList { get; set; }
/// <summary>
/// Gets or sets the callback that is called when nothing is found.
/// </summary>
public Action<EncodedTextWriter, BlockHelperOptions, Context, Arguments>? NothingFound { get; set; }
/// <inheritdoc />
protected override string HelperName { get; }
public ForEachHandlebarsBlock<TModel> WithGetList(Func<TModel, IEnumerable<object>>? callback)
{
this.GetList = callback;
return this;
}
public ForEachHandlebarsBlock<TModel> WithNothingFoundText(
Action<EncodedTextWriter, BlockHelperOptions, Context, Arguments>? callback)
{
this.NothingFound = callback;
return this;
}
/// <summary>
/// Sets the output to write out text when no items are found.
/// </summary>
/// <param name="text">The text to write out.</param>
/// <returns>The same object for chained methods.</returns>
public ForEachHandlebarsBlock<TModel> WithNothingFoundText(string text)
{
this.NothingFound = (
output,
_1,
_2,
_3) => output.Write(text);
return this;
}
/// <inheritdoc />
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<TModel>),
context.Value.GetType()));
}
IEnumerable<object>? 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);
}
}
}