@mohsensami/template-engine
v1.1.0
Published
A simple template engine for Express.js
Downloads
27
Maintainers
Readme
@mohsensami/template-engine
A simple and lightweight template engine for Express.js using {{key}} syntax for dynamic templating. It’s easy to use, has no dependencies, and is perfect for quick and minimalistic projects.
Features
- Simple Syntax: Use
{{key}}to inject dynamic data into your templates. - Lightweight: No dependencies other than Node.js built-in modules.
- Express Compatible: Fully supports Express.js’s
app.enginefor seamless integration. - Flexible: Works with any
.tplfile in your views directory.
Installation
Install the package via npm:
npm install @mohsensami/template-engineUsage
Setting Up in Express.js Here’s how to integrate @mohsensami/template-engine into your Express.js application:
- Import and Configure the Template Engine:
const express = require("express");
const path = require("path");
const templateEngine = require("@mohsensami/template-engine");
const app = express();
// Register the template engine with Express
app.engine("tpl", templateEngine.renderFile);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "tpl");- Create a Template File: In the views directory, create a file named index.tpl:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{title}}</title>
</head>
<body>
<h1>{{message}}</h1>
</body>
</html>- Render the Template: Define a route in your application and render the template with dynamic data:
app.get("/", (req, res) => {
res.render("index", { title: "Welcome!", message: "This is a custom template engine!" });
});- Run Your App: Start the server:
node app.jsVisit http://localhost:3000 in your browser to see your rendered template.
How It Works
The @mohsensami/template-engine uses the {{key}} syntax to dynamically replace placeholders in your .tpl files with values from the data object passed to res.render.
For example, given the template:
<h1>{{title}}</h1>
<p>{{description}}</p>And the data object:
{ title: "Hello, World!", description: "This is a simple template engine." }
The rendered output will be:
html Copy code
<h1>Hello, World!</h1>
<p>This is a simple template engine.</p>License
This project is licensed under the MIT License. See the LICENSE file for details.
Contributing
Contributions are welcome! Feel free to submit issues or pull requests to improve this package.
Author
Created by Mohsen Sami.
Links
GitHub Repository - https://github.com/mohsensami/template-engine npm Package - https://www.npmjs.com/package/@mohsensami/template-engine
