Welcome to the Comprehensive Guide to LiquidJS Template Engine
LiquidJS is a lightweight, safe, and expressive template engine in JavaScript. It provides a clean, Ruby on Rails inspired syntax for building dynamic templates in a maintainable way. In this guide, we’ll go through dozens of useful API examples to help you get started with LiquidJS, featuring practical code snippets and a complete application example.
Getting Started with LiquidJS
const { Liquid } = require('liquidjs'); const engine = new Liquid();
API Examples
Rendering Templates
const template = '{{name | capitalize}}'; engine.parseAndRender(template, { name: 'liquidjs' }) .then(result => console.log(result)); // Outputs: Liquidjs
Using Filters
const template = '{{ "Hello World"| downcase }}'; engine.parseAndRender(template) .then(result => console.log(result)); // Outputs: hello world
Conditional Logic
const template = '{% if user %}Hello, {{ user.name }}{% else %}Hello, anonymous{% endif %}'; engine.parseAndRender(template, { user: { name: 'Alice' } }) .then(result => console.log(result)); // Outputs: Hello, Alice
Iteration
const template = '{% for item in array %}{{ item }}, {% endfor %}'; engine.parseAndRender(template, { array: [1, 2, 3] }) .then(result => console.log(result)); // Outputs: 1, 2, 3,
Advanced Filters
const template = '{{ "2023-10-10" | date: "%b %d, %Y" }}'; engine.parseAndRender(template) .then(result => console.log(result)); // Outputs: Oct 10, 2023
Building a Web Application with LiquidJS
Below is an example of a basic Node.js application using LiquidJS to render dynamic HTML pages from templates.
Step 1: Install Dependencies
npm install liquidjs express
Step 2: Create the Application
const express = require('express'); const { Liquid } = require('liquidjs'); const app = express(); const engine = new Liquid(); app.engine('liquid', engine.express()); app.set('views', './views'); app.set('view engine', 'liquid'); app.get('/', (req, res) => { res.render('index', { title: 'Hello LiquidJS', message: 'Welcome to LiquidJS with Node.js' }); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
Step 3: Create the Template (views/index.liquid)
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ message }}</h1> </body> </html>
Conclusion
LiquidJS is a powerful and flexible templating engine that can help you create dynamic and maintainable web applications with ease. This guide provided an overview of many useful APIs with code examples, and demonstrated how to build a simple web application using LiquidJS and Express.
Happy coding!
Hash: 7482054a3bb21e7ef10dd3c329e1bf0b30285500d42d72676090b7c330027715