Adding Auto Caching to Our Template Engine

shadowtime2000

shadowtime2000

Posted on January 11, 2021

Adding Auto Caching to Our Template Engine

In one of my articles, I showed you how to create a simple JS template engine. In this article I will show you how to add simple caching to the compilation of our templates.

How Caching Works with JS Template Engines

Caching with our template engine is pretty simple. We just keep a key value object and use template strings as keys and functions as values. This will make subsequent uses of a template faster.

Implementing it inside Compile

All our compile function is this:

const compile = (template) => {
    return new Function("data", "return " + compileToString(template))
}
Enter fullscreen mode Exit fullscreen mode

Let's rename this to compileToFunction.

const compileToFunction = (template) => {
    return new Function("data", "return " + compileToString(template))
}
Enter fullscreen mode Exit fullscreen mode

Now let's create a cache. We will use a Map for this.

const cache = new Map();
Enter fullscreen mode Exit fullscreen mode

Now let's add a compile function which uses this cache.

All we need to do is check if the cache.has(template). If not, we need to create it and set it. If it does have it, we just need to return it.

const compile = (template) => {
    if (cache.has(template)) {
        return cache.get(template);
    } else {
        const compiledFunction = compileToFunction(template);
        cache.set(template, compiledFunction);
        return compiledFunction;
    }
}
Enter fullscreen mode Exit fullscreen mode

Changing our Render Function

Currently our render function just uses some Regex to replace all the values.

var render = (template, data) => {
    return template.replace(/{{(.*?)}}/g, (match) => {
        return data[match.split(/{{|}}/).filter(Boolean)[0]]
    })
}
Enter fullscreen mode Exit fullscreen mode

I think we should change it to use compile under the hood for faster automatic caching. It is pretty simple to implement, we just need to run compile and then run that function with data.

const render = (template, data) => {
    return compile(template)(data);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial I showed how to extend the template engine we made in a previous post with caching for faster compilation and rendering.

Other Articles You Might Like

  1. Creating a JS Template Engine
  2. ๐Ÿš€14 JS Template Engines๐Ÿš€
๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
shadowtime2000
shadowtime2000

Posted on January 11, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Introduction to Nodejs and Express
javascript Introduction to Nodejs and Express

October 17, 2021

Adding Auto Caching to Our Template Engine
javascript Adding Auto Caching to Our Template Engine

January 11, 2021

ยฉ TheLazy.dev

About