Introduction to LiquidJS
LiquidJS is a powerful templating engine for JavaScript, designed to create dynamic and flexible web pages. Similar to other templating engines, it allows you to use plain text with embedded variables and control structures. Let’s dive into the capabilities of LiquidJS with several API examples.
Basic Syntax
LiquidJS uses double curly braces {{}}
for output and curly brace percent {% %}
for logic such as conditions and loops. Here’s a basic example:
const Liquid = require('liquidjs'); const engine = new Liquid(); const template = '{{ greeting }}, {{ name }}!'; const context = { greeting: 'Hello', name: 'World' }; engine.parseAndRender(template, context).then(result => { console.log(result); // Output: Hello, World! });
Conditional Statements
You can use {% if %}
, {% else %}
, and {% endif %}
for conditionals:
const template = ` {% if user %} Welcome, {{ user.name }}! {% else %} Welcome, Guest! {% endif %} `; engine.parseAndRender(template, { user: { name: 'Alice' } }) .then(console.log); // Output: Welcome, Alice! engine.parseAndRender(template, {}) .then(console.log); // Output: Welcome, Guest!
Loops
Loops can be created using {% for %}
:
const template = ` {% for product in products %} - {{ product.name }}: {{ product.price }} {% endfor %} `; const context = { products: [ { name: 'Apple', price: '$1' }, { name: 'Banana', price: '$0.5' }, ] }; engine.parseAndRender(template, context).then(console.log); // Output: // - Apple: $1 // - Banana: $0.5
Filters
Filters allow you to modify the output. Here’s an example:
const template = '{{ "hello world" | upcase }}'; engine.parseAndRender(template).then(result => { console.log(result); // Output: HELLO WORLD });
Creating a Simple App
Let’s create a simple web application that uses these features:
const express = require('express'); const Liquid = require('liquidjs'); const app = express(); const engine = new Liquid(); app.engine('liquid', engine.express()); // Register `.liquid` files app.set('views', './views'); // Set the views directory app.set('view engine', 'liquid'); // Set Liquid as the view engine app.get('/', (req, res) => { res.render('index', { title: 'My Dynamic App', user: { name: 'John Doe' }, products: [{ name: 'Laptop', price: '$999' }] }); }); app.listen(3000, () => console.log("Server running on http://localhost:3000")); // index.liquid in views /*{{ title }} Welcome, {{ user.name }}!
-
{% for product in products %}
- {{ product.name }}: {{ product.price }} {% endfor %}
This simple app displays a personalized welcome message and a list of products. Start your server and navigate to http://localhost:3000 to see it in action.
By utilizing the features of LiquidJS, you can easily create dynamic and maintainable web applications.
Hash: 7482054a3bb21e7ef10dd3c329e1bf0b30285500d42d72676090b7c330027715