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