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/Nitride.Handlebars/ApplyContentHandlebarsTemplate.cs
Dylan R. E. Moonfire 78054ee2a7 feat: initial release
2021-09-07 00:15:45 -05:00

75 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
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 ApplyContentHandlebarsTemplate<TModel> : NitrideOperationBase
{
private readonly HandlebarsTemplateCache cache;
public ApplyContentHandlebarsTemplate(HandlebarsTemplateCache cache)
{
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.CheckNotNull(x => x.CreateModelCallback);
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 ApplyContentHandlebarsTemplate<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));
}
}
}