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/ApplyStyleTemplate.cs
D. Moonfire 2892ec3445
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
feat!: added cancellation token support to pipelines and operations
2023-01-17 19:24:09 -06:00

74 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using FluentValidation;
using HandlebarsDotNet;
using MfGames.Gallium;
using MfGames.Nitride.Contents;
using MfGames.Nitride.Generators;
namespace MfGames.Nitride.Handlebars;
/// <summary>
/// An operation that applies a common or shared template on the content of
/// a document that includes theme or styling information.
/// </summary>
[WithProperties]
public partial class ApplyStyleTemplate : OperationBase
{
private readonly HandlebarsTemplateCache cache;
private readonly IValidator<ApplyStyleTemplate> validator;
public ApplyStyleTemplate(
IValidator<ApplyStyleTemplate> 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; }
/// <summary>
/// Gets or sets the callback used to determine which template to use
/// for a given entity. This lets one have a per-page template change.
/// </summary>
public Func<Entity, string>? GetTemplateName { get; set; }
public IHandlebars? Handlebars { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(
IEnumerable<Entity> input,
CancellationToken cancellationToken = default)
{
// Make sure we have sane data.
this.validator.ValidateAndThrow(this);
// Create and set up the Handlebars.
return input.SelectEntity<ITextContent>(this.Apply);
}
private Entity Apply(
Entity entity,
ITextContent content)
{
object model = this.CreateModelCallback!(entity);
string name = this.GetTemplateName!(entity);
HandlebarsTemplate<object, object> template =
this.cache.GetNamedTemplate(name);
string result = template(model!);
return entity.SetTextContent(result);
}
}