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/RenderContentTemplate.cs

64 lines
1.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using FluentValidation;
2022-09-06 05:53:22 +00:00
using MfGames.Gallium;
using HandlebarsDotNet;
2022-09-06 05:53:22 +00:00
using MfGames.Nitride.Contents;
2022-09-06 05:53:22 +00:00
namespace MfGames.Nitride.Handlebars;
/// <summary>
/// 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.
/// </summary>
[WithProperties]
public partial class RenderContentTemplate : OperationBase
{
private readonly HandlebarsTemplateCache cache;
private readonly IValidator<RenderContentTemplate> validator;
public RenderContentTemplate(
IValidator<RenderContentTemplate> validator,
HandlebarsTemplateCache cache)
{
this.validator = validator;
this.cache = cache;
}
/// <summary>
/// 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.
/// </summary>
public Func<Entity, object>? CreateModelCallback { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
2022-07-09 04:52:10 +00:00
return input.SelectEntity<HasHandlebarsTemplate, ITextContent>(this.Apply);
}
2022-07-09 04:52:10 +00:00
private Entity Apply(
Entity entity,
HasHandlebarsTemplate _,
ITextContent content)
{
string text = content.GetText();
HandlebarsTemplate<object, object> template = this.cache.GetLiteralTemplate(text);
object model = this.CreateModelCallback!(entity);
string result = template(model!);
return entity
.Remove<HasHandlebarsTemplate>()
.SetTextContent(result);
}
}