We’re currently working on a project that communicates with a third-party API. The response data is returned in JSON format, so we’ve opted to take the response and pipe it into a JavaScript templating engine.

The challenge: Finding the perfect JavaScript templating engine.

Well, sort of. The thing is, finding a templating engine is pretty easy. There are plenty of them. And many of them work the same way. I’m not sure I’m in a place where I could say I have a “favorite.”

The Perfect JavaScript Templating Engine

Instead, it’s more about finding one that achieves what we need. So what works for one project may work for another project or it may not.

For this project, we’ve opted to use tplite.

The Perfect JavaScript Templating Engine: tplite

From the project’s homepage:

Component based on micro javascript template engine.

Sound simple enough, doesn’t it? Here’s the thing, though:

  • it’s a really small engine,
  • it supports variables, expressions,
  • it has support for conditionals and loops,
  • and the documentation is solid on how to use it.

The repository has a solid example, but to show you how easy it is to get up and running with this from purely a JavaScript perfect, take a look at how easy it is:

And if you’re using NPM to manage your packages, including it is as easy as it gets:

To Get Started

If this particular engine seems interesting to you and you have NPM installed, here’s what you need to do to get started:

  1. Create package.json and include the above code.
  2. Run npm install or npm update if you’re already using it.
  3. Include the code using wp_enqueue_script.

Here’s the thing, though: The script will be located in a node_modules directory so your code may look something like this:

But if you opt not to distribute that particular directory with your final project, you can move the file to an assets directory or whatever it is you opt to do to make it as easy as possible to include in your work.

Regardless, once it’s registered and enqueued, you can use it like in the example earlier in the post.

A Word About Licensing

For what it’s worth if you’re working in WordPress and you’re concerned about whether or not it will be compatible with its license, tplite is under MIT so, yes, it’s a compatible license.

Category:
Resources
Tags: