76 lines
2.4 KiB
C#
76 lines
2.4 KiB
C#
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
|
||
|
using FluentValidation;
|
||
|
|
||
|
using Gallium;
|
||
|
|
||
|
using HandlebarsDotNet;
|
||
|
|
||
|
using Nitride.Contents;
|
||
|
|
||
|
namespace 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>
|
||
|
public class RenderContentTemplate<TModel> : OperationBase
|
||
|
{
|
||
|
private readonly HandlebarsTemplateCache cache;
|
||
|
|
||
|
// TODO: This does not use [WithProperties] because the source generator hasn't been taught how to do generics.
|
||
|
|
||
|
private readonly IValidator<RenderContentTemplate<TModel>> validator;
|
||
|
|
||
|
public RenderContentTemplate(IValidator<RenderContentTemplate<TModel>> 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, TModel>? CreateModelCallback { get; set; }
|
||
|
|
||
|
/// <inheritdoc />
|
||
|
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
|
||
|
{
|
||
|
this.validator.ValidateAndThrow(this);
|
||
|
|
||
|
return input.ForEachEntity<HasHandlebarsTemplate, ITextContent>(this.Apply);
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Sets the callback for the template and returns the operation to
|
||
|
/// chain operations.
|
||
|
/// </summary>
|
||
|
/// <param name="callback">The callback to set.</param>
|
||
|
/// <returns>The ApplyContentHandlebarsTemplate to chain requests.</returns>
|
||
|
public RenderContentTemplate<TModel> WithCreateModelCallback(Func<Entity, TModel>? callback)
|
||
|
{
|
||
|
this.CreateModelCallback = callback;
|
||
|
return this;
|
||
|
}
|
||
|
|
||
|
private Entity Apply(Entity entity, HasHandlebarsTemplate _, ITextContent content)
|
||
|
{
|
||
|
// Create the model using the callback.
|
||
|
TModel model = this.CreateModelCallback!(entity);
|
||
|
|
||
|
// Create a template from the contents.
|
||
|
string text = content.GetText();
|
||
|
HandlebarsTemplate<object, object> template = this.cache.GetLiteralTemplate(text);
|
||
|
|
||
|
// Render the template and create a new entity with the updated
|
||
|
// text.
|
||
|
string result = template(model!);
|
||
|
|
||
|
return entity.Remove<HasHandlebarsTemplate>().SetTextContent(new StringTextContent(result));
|
||
|
}
|
||
|
}
|