Design and implement a template engine–part 2

In the Design and implement a template engine – part 1 I mentioned about a better solution: Reuse Razor Engine. In the post, I go in detail of how to implement it. But, first, we need to know some concepts:

Concepts

  1. Template Engine: Use to render a template into string
  2. Template Model Builder: Build the Model object which is used to fill in the data in template
  3. Template Model Expander: Expand the Model object with more properties
  4. And Template: the template

Implementation

The implementation assume that you already know about dynamic object and Razor Syntax (which is used in MVC – Views)

ITemplateModelExpander is the one that will be implemented in many classes. As its purpose, we want to expand the dynamic object to build up a real Model for the template.

Next we will see how we define a Template Model Builder.

It does 1 main thing: Build; which builds the Model object (of course, dynamic object) using expanders. That’s why you see 3 more methods related to Expander.

Then I make a simple implementation for the Model Builder:

Pretty simple right Smile

Let’s talk about Template, I have this simple interface:

Define it as interface gives me power to change the template type. Even though, I just have Razor template for now:

You might wander why do I not inject template property directly in the constructor? Because, I want to resolve the ITemplate instance using an IoC container, such as Windsor and wire up with correct ITemplateModelBuilder which is StandardTemplateModelBuilder in this case. (I will show you how to use it later)

The last part, the Template Engine:

Very simple. It just render an ITemplate instance.

The implementation is based on Razor Engine

It asks the ModelBuilder from Template to build up the dynamic model object which is used to populate the template.

Usage

Have a look at this Unit Test:

I setup Engine, ModelBuilder, and Razor Template. These objects can be wire up automatically by IoC, see below

And very simple implementation for SampleByNameExpander:

If you want to expand the Model with more properties that make sense to your application, you can add as many as possible. Just make sure you add the expander for the ModelBuilder of the Template you want. Or you can create a big giant Expander which will expose lot of properties at once. However, I will not encourage that. It is much more maintainable with simple small classes.

And, that’s it. Hope it help Smile

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: