3.0 KiB
The Liquid template language is a simple, expressive, and powerful templating language originally created by Shopify. It's designed to enable developers to embed dynamic content in static web pages, particularly in e-commerce sites, but it's also widely used in static site generators like Jekyll and other web applications.
Key Features of Liquid:
-
Simple Syntax:
- Liquid uses a combination of tags, filters, and objects to embed logic and dynamic content within templates.
- Tags: Control the logic (e.g.,
{% if %},{% for %},{% assign %}). - Objects: Output data from variables (e.g.,
{{ product.title }}). - Filters: Modify the output of objects (e.g.,
{{ product.title | upcase }}).
-
Safe and Secure:
- Liquid ensures that template authors can't execute arbitrary code, providing a secure way to embed logic within templates.
-
Designed for Performance:
- It's optimized for speed and efficiency, making it suitable for high-traffic e-commerce sites.
-
Extensible:
- Liquid allows for custom filters and tags, enabling developers to extend its functionality as needed.
Basic Syntax Examples:
-
Variables:
{{ variable_name }} -
Tags:
-
Control structures, such as loops and conditionals:
{% if product.available %} This product is available. {% else %} This product is out of stock. {% endif %} -
Iteration over collections:
{% for product in products %} {{ product.title }} {% endfor %}
-
-
Filters:
- Used to modify output:
{{ "hello world" | upcase }} <!-- Outputs: HELLO WORLD --> {{ product.price | divided_by: 100 }} <!-- Converts cents to dollars -->
- Used to modify output:
Common Use Cases:
-
E-commerce Sites:
- Display product information, handle shopping cart logic, and render customer data dynamically.
-
Static Site Generators:
- Used in Jekyll to render dynamic content on static websites.
-
Content Management Systems:
- Integrates with CMS platforms to allow for dynamic content rendering.
Example in an E-commerce Context:
<!DOCTYPE html>
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
<h1>{{ shop.name }}</h1>
<ul>
{% for product in collections.frontpage.products %}
<li>
<h2>{{ product.title }}</h2>
<p>{{ product.description }}</p>
<p>Price: {{ product.price | divided_by: 100 | currency }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
In this example, the Liquid template dynamically generates a list of products, displaying their title, description, and price.
Conclusion
Liquid is a versatile and secure templating language well-suited for applications where dynamic content needs to be rendered safely and efficiently. Its straightforward syntax and extensive use in platforms like Shopify and Jekyll make it a popular choice among developers.