A simple templating engine built in JavaScript to render dynamic HTML content by injecting variables, loops, and conditionals. This project is useful for learning about custom template rendering logic.
- Variable Injection: Use
{{ variableName }}to inject data into templates. - Conditionals: Add simple if-else logic with
{% if condition %}...{% endif %}. - Loops: Iterate over arrays or objects with
{% for item in array %}...{% endfor %}. - Template Caching: Parsed templates are cached for faster rendering.
-
Clone the repository:
git clone https://github.com/Martin322s/custom-templating-engine.git
-
Navigate into the project directory:
cd custom-templating-engine -
Install dependencies (if any):
npm install
-
Register a Template: First, register your template with the engine:
const TemplateEngine = require('./src/TemplateEngine'); const engine = new TemplateEngine(); engine.registerTemplate('example', ` <h1>{{ title }}</h1> <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> `);
-
Render the Template: Pass the registered template along with data to render the HTML:
const output = engine.render('example', { title: 'Shopping List', items: ['Apples', 'Bananas', 'Oranges'] }); console.log(output);
For the template above, the output will be:
<h1>Shopping List</h1>
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ul>-
Variables: Insert dynamic data with
{{ variableName }}. The value is pulled from the data object provided at render time.<h1>{{ title }}</h1>
-
Conditionals: Use
{% if condition %}for conditional rendering.{% if isAdmin %} <p>Welcome, Admin!</p> {% endif %} -
Loops: Iterate over arrays with
{% for item in array %}.<ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul>
The engine automatically caches parsed templates for improved performance. You can customize or clear the cache by modifying the cache.js module.
your-templating-library/
│
├── src/
│ ├── TemplateEngine.js # Core engine logic
│ ├── utils.js # Utility functions
│ ├── parser.js # Template parsing logic
│ ├── renderer.js # Template rendering logic
│ ├── cache.js # Caching compiled templates
│ └── index.js # Main entry point
│
├── templates/ # Folder to store templates
│ └── base.html # A sample template
│
├── test/ # Test folder
│ └── TemplateEngine.test.js # Test cases for templating engine
│
├── README.md # Project documentation
└── package.json # Project dependencies
To run unit tests for the templating engine:
-
Install
jestas a dev dependency:npm install jest --save-dev
-
Add the following script to
package.json:"scripts": { "test": "jest" }
-
Run the tests:
npm test
This project is licensed under the MIT License. See the LICENSE file for details.