FillTemplate-Methode als Erweiterung hinzugefügt. Option zum Schreiben von Platzhaltern als Wörterbuch hinzugefügt.

This commit is contained in:
Developer 02
2024-06-10 16:19:48 +02:00
parent a8b3e88f09
commit e22d030fa2
4 changed files with 57 additions and 30 deletions

View File

@@ -17,35 +17,20 @@ namespace DigitalData.EmailProfilerDispatcher.Application.Services
{
}
public string ApplyTemplate(string template, params object[] models) => FillTemplate(template: template, models: models);
public async Task<DataResult<int>> CreateWithTemplateAsync(EmailOutCreateDto createDto, params object[] models)
{
createDto.EmailSubj = FillTemplate(createDto.EmailSubj, models);
createDto.EmailBody = FillTemplate(createDto.EmailBody, models);
createDto.EmailSubj = createDto.EmailSubj.FillTemplate(models);
createDto.EmailBody = createDto.EmailBody.FillTemplate(models);
return await base.CreateAsync(createDto);
}
public static string FillTemplate(string template, params object[] models)
public async Task<DataResult<int>> CreateWithTemplateAsync(EmailOutCreateDto createDto, Dictionary<string, string> placeholders, params object[] models)
{
foreach(var model in models)
{
var properties = model.GetType().GetProperties();
createDto.EmailSubj = createDto.EmailSubj.FillTemplate(placeholders);
createDto.EmailBody = createDto.EmailBody.FillTemplate(placeholders);
foreach (var property in properties)
{
var attribute = property.GetCustomAttribute<TemplatePlaceholderAttribute>();
if (attribute != null)
{
var value = property.GetValue(model)?.ToString();
template = template.Replace(attribute.Placeholder, value);
}
}
}
return template;
return await CreateWithTemplateAsync(createDto, models: models);
}
}
}

View File

@@ -0,0 +1,42 @@
using DigitalData.EmailProfilerDispatcher.Domain.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DigitalData.EmailProfilerDispatcher.Application
{
public static class TemplateExtensions
{
public static string FillTemplate(this string template, params object[] models)
{
foreach (var model in models)
{
var properties = model.GetType().GetProperties();
foreach (var property in properties)
{
var attribute = property.GetCustomAttribute<TemplatePlaceholderAttribute>();
if (attribute != null)
{
var value = property.GetValue(model)?.ToString();
template = template.Replace(attribute.Placeholder, value);
}
}
}
return template;
}
public static string FillTemplate(this string template, Dictionary<string, string> placeholders)
{
foreach (var ph in placeholders)
template = template.Replace(ph.Key, ph.Value);
return template;
}
}
}