Email Templates
Since #Script is intuitive and approachable to non-programmers it's useful in several Business Activities that are better served by non-technical Business employees like Marketers, Designers, Copywriters, etc. Generating and Previewing email templates are one example of this:
Order Confirmation Email Example
Implementation
This example uses this simple Service below to generate the HTML and plain-text email previews of this email template:
EmailTemplatesService.cs
using System.Linq;
using System.Collections.Generic;
using ServiceStack;
using ServiceStack.Script;
using ServiceStack.IO;
namespace SharpScript
{
[Route("/emails/order-confirmation/preview")]
public class PreviewHtmlEmail : IReturn<PreviewHtmlEmailResponse>
{
public string EmailTemplate { get; set; }
public string HtmlTemplate { get; set; }
public string PreviewCustomerId { get; set; }
}
public class PreviewHtmlEmailResponse
{
public string HtmlEmail { get; set; }
public string TextEmail { get; set; }
}
public class EmailTemplatesServices : Service
{
public ICustomers Customers { get; set; }
public object Any(PreviewHtmlEmail request)
{
var customer = Customers.GetCustomer(request.PreviewCustomerId)
?? Customers.GetAllCustomers().First();
var context = new ScriptContext {
PageFormats = { new MarkdownPageFormat() },
Args = {
["customer"] = customer,
["order"] = customer.Orders.LastOrDefault(),
}
}.Init();
context.VirtualFiles.WriteFile("email.md", request.EmailTemplate);
context.VirtualFiles.WriteFile("layout.html", request.HtmlTemplate);
var textEmail = new PageResult(context.GetPage("email")).Result;
var htmlEmail = new PageResult(context.GetPage("email")) {
Layout = "layout",
PageTransformers = { MarkdownPageFormat.TransformToHtml }
}.Result;
return new PreviewHtmlEmailResponse {
TextEmail = textEmail,
HtmlEmail = htmlEmail,
};
}
}
}
The source code for this email-templates.html page shows the client preview itself is just using Bootstrap Tabs that only uses this custom javascript:
<script>
$("FORM").ajaxPreview({
success: function(r) {
$("#html-preview").html(r.htmlEmail);
$("#text-preview").html(r.textEmail);
}
})
</script>
Which calls the generic ajaxPreview jQuery plugin in default.js to make an ajax request on every text box change.