An Introduction to Apex Perseus & Mustache

Bob Calco 03.05.2018

Look, a mustache!

Mustache is a declarative template programming language designed to be simple yet sufficiently powerful to generate anything digital under the sun from well-structured data.

Its name is derived from the fact that variable values are interpolated into template text in blocks delimited by double squiggly lines (i.e., “{{” and “}}” to begin and end a block, respectively).

Well you have to admit, they do kinda look like mustaches.

What’s it good for?

Templates in Mustache are “logic-less,” meaning that the template language itself is, by design, not Turing-complete. Lack of Turing-completeness essentially means that the language does not permit complex and (more to the point) possibly erroneous business logic, such as you might be tempted or even encouraged to implement in a full-on scripting language like PHP, to be hard-coded into a template.

This ensures, among other useful properties, that the templates are not yet another place in the code base where slopping through spaghetti code can happen. You put logic where it belongs, in the logic layer of your application. You boil, mix and stir your code there, salting to taste.

In software engineering this is called “separation of concerns,” and it is generally and rightly regarded as a Good Idea in multiple disciplines, including culinary art.

In other words, during source code preparation, you keep your meatballs and sauce concerns strictly separated from your pasta concerns and your fresh herb and shredded cheese concerns, until at last everything is ready and the disparate elements are beautifully assembled during plate-up, creating a fabulous, hand-crafted customer experience. Be sure to use freshly-chopped herbs and serve it up with a nice Chianti, or perhaps a Brunello.

Such engineering craftsmanship also has the benefit of encouraging clean-up as you go—i.e., continuous “refactoring”—which is always a good idea, too.

With Turing-complete template languages like PHP, there is literally no place safe from slopping through spaghetti code, not even the otherwise declarative, pure-data confines of standard HTML tags. Indeed, PHP’s original concept and raison d’être is to help you and your HTML become one with the spaghetti. Just throw it all in a pot, cook it till you smell smoke, and slam it on the plate. Violá.

To be sure, spaghetti cooked in this manner can taste great on the plate, and maybe get served faster than professional techniques allow, but what a mess it leaves behind for you (and more likely others) to clean up later!

Most experienced software engineers agree that swift and merciless public caning is the proper punishment for such embarassing design pattern infractions as Turing-complete template engines encourage developers to commit.

So to avoid much pain applied to your posterior, you really ought to consider (among other best practices) using a logic-less template engine like Mustache whenever you need to generate code on the fly.

Note the righteous mustache on the schoolmaster in the above actual photograph of a young, brash developer who thought it would be a good idea to use a Turing-complete scripting language to generate HTML code for the school website. That might be his classmate, Alan Turing, off to the left, also in trouble for egging him on.

Tisk, Tisk.

So how do I avoid such a red-rumped fate?

Apex Perseus aims in its initial release targeting Embarcadero Delphi and C++ Builder to provide a commercial-grade implementation of Mustache as part of a fledgeling set of domain-specific parsing APIs to which we refer collectively as the “Perseus Parsing System.” The goal of the Perseus Parsing System is to support generative and language-oriented programming “in the large” in our downstream products.

Apex Perseus comes not only with a set of SDKs for regular expressions and domain-specific parsing, but also a framework for structuring service and other non-GUI applications, which we call Apex Commander.

Apex Perseus therefore also provides a handy standalone command line application that exposes the various SDKs as utilities for common programming and data transformation tasks.

This command line application, called perseus (as you might imagine), is itself built using Apex Commander and, aside from exemplifying our “drink your own champagne” philosophy (I mean really, who likes to eat dog food?), it is a good example of what you can build with Apex Commander.

(It is also available separately, if you aren’t a software developer or a Delphi/C++ Builder coder.)

OK, grow me some Mustache, already!

Unless you’re old enough, growing a mustache can take a while. For your convenience in the meantime, feel free to cut and paste the following Mustache code to your upper lip, then save it in a file called penitent.pmt.

penitent.pmt:

{{#sins}}
Forgive me, {{absolver}}, for I have sinned! {{sin}}
WHACK!
Thank you, {{punisher}}, may I have another?

{{/sins}}
No, you have no more sins for which to atone, {{sinner}}. 

Now go, and sin no more.

(By convention, we assume a *.pmt file extension for “Perseus Mustache Templates” but if you buy our SDK, you can build your own processing engine and call them whatever you want.)

In order to see justice delivered swiftly by the blade of Perseus’ gorgon-slaying sword, we’re going to need a sinner with some sins. You can choose to record these in a JSON, XML or EDN file.

For now, we’ll use JSON to log the career arc of a young Alan Turing, had he grown up in today’s competitive IT market (spoiler alert!— it’s a classic tale of redemption with a modern, and decidedly less verbose, twist):

sins.json:

{
  "sinner": "Alan Turing",
  "sins" : [
    {
      "sin": "I used PHP to code our school website.",
      "absolver": "Schoolmaster",
      "punisher": "Sir"
    },
    {
      "sin": "I dabbled in ASP.NET on the side.",
      "absolver": "Employer",
      "punisher": "HR Lady"
    },
    {
      "sin": "I thought JSP's were a good idea.",
      "absolver": "Terence Parr",
      "punisher": "Monster.com"
    }
  ]
}

Run the perseus command line application as follows:

perseus generate -d=sins.json -t=penitent.pmt -o=atonement.txt

You should now find a file named atonement.txt with the following lines of text, as if Joseph Conrad himself had penned them:

Forgive me, Schoolmaster, for I have sinned! I used PHP to code our school website.
WHACK!
Thank you, Sir, may I have another?

Forgive me, Employer, for I have sinned! I dabbled in ASP.NET on the side.
WHACK!
Thank you, HR Lady, may I have another?

Forgive me, Terence Parr, for I have sinned! I thought JSP's were a good idea.
WHACK!
Thank you, Monster.com, may I have another?

No, you have no more sins for which to atone, Alan Turing.

Now go, and sin no more.

Pretty cool, huh?

Not only is the data cleanly separated from the template code, there isn’t a hint of a for-loop or array access that you would otherwise hand-code into your run-of-the-mill Turing-complete template language, risking off-by-one and other bonehead errors quite unnecessarily.

Anything You Can Do We Can Do Meta

For maximum Joseph Conrad effect, you can even use Mustache templates to create new Mustache templates and data files on the fly in a data transformation and artifact generation pipeline!

Like a typical Conrad novel with the narrator narrating another narrator’s narration, this can get pretty meta. We’ll demonstrate the power of this strategy in subsequent posts focusing more specifically on code generation.

In our next post, we’ll introduce Apex Commander and show off some Mustache code generation in the service of building command line applications with multiple entry points using Commander’s plug-in API.

Be sure to bring your own garlic bread for that one!