using System; using System.Collections.Generic; using FluentValidation; using HandlebarsDotNet; using MfGames.Gallium; using MfGames.Nitride.Contents; namespace MfGames.Nitride.Handlebars; /// /// An operation that uses the content to create a template that is then /// applied against the content and metadata and then replaces the content /// of that entity. /// [WithProperties] public partial class RenderContentTemplate : OperationBase { private readonly HandlebarsTemplateCache cache; private readonly IValidator validator; public RenderContentTemplate( IValidator validator, HandlebarsTemplateCache cache) { this.validator = validator; this.cache = cache; } /// /// Gets or sets the callback used to create a model from a given /// entity. This allows for the website to customize what information is /// being passed to the template. /// public Func? CreateModelCallback { get; set; } /// public override IEnumerable Run(IEnumerable input) { this.validator.ValidateAndThrow(this); return input.SelectEntity( this.Apply); } private Entity Apply( Entity entity, HasHandlebarsTemplate _, ITextContent content) { string text = content.GetText(); HandlebarsTemplate template = this.cache.GetLiteralTemplate(text); object model = this.CreateModelCallback!(entity); string result = template(model!); return entity .Remove() .SetTextContent(result); } }