Convert Figma logo to code with AI

Shopify logoliquid

Liquid markup language. Safe, customer facing template language for flexible web apps.

11,005
1,375
11,005
356

Top Related Projects

Logic-less Ruby templates.

Minimal templating on steroids.

21,636

Pug – robust, elegant, feature rich template engine for Node.js

3,758

HTML Abstraction Markup Language - A Markup Haiku

11,931

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Quick Overview

Liquid is a flexible and secure template language developed by Shopify. It's used for building e-commerce websites and is the foundation for themes in Shopify's platform. Liquid allows developers to create dynamic content and customize the look and feel of online stores without compromising security.

Pros

  • Easy to learn and use, with a syntax similar to other templating languages
  • Highly extensible through custom filters and tags
  • Secure by design, preventing arbitrary code execution
  • Well-documented and supported by a large community

Cons

  • Limited built-in functionality compared to some other templating languages
  • Performance can be an issue with complex templates
  • Debugging can be challenging, especially for nested includes
  • Some advanced features are Shopify-specific and not available in open-source implementations

Code Examples

  1. Basic variable output:
<h1>{{ page.title }}</h1>
<p>Welcome, {{ customer.name }}!</p>

This code outputs the page title and customer name using Liquid variables.

  1. Conditional statement:
{% if product.available %}
  <p>In stock</p>
{% else %}
  <p>Sold out</p>
{% endif %}

This example checks if a product is available and displays the appropriate message.

  1. Looping through a collection:
<ul>
{% for product in collection.products %}
  <li>{{ product.title }} - {{ product.price | money }}</li>
{% endfor %}
</ul>

This code creates a list of products in a collection, displaying their titles and prices.

  1. Using filters:
{{ "hello world" | capitalize | reverse }}

This example demonstrates the use of filters to manipulate string output.

Getting Started

To use Liquid in your project:

  1. Install the Liquid gem:
gem install liquid
  1. Create a new Liquid template:
template = Liquid::Template.parse("Hello, {{ name }}!")
  1. Render the template with variables:
output = template.render("name" => "John")
puts output  # Outputs: Hello, John!

For more advanced usage and integration with web frameworks, refer to the Liquid documentation and your specific framework's guidelines.

Competitor Comparisons

Logic-less Ruby templates.

Pros of Mustache

  • Simpler syntax with fewer features, making it easier to learn and use
  • Language-agnostic, with implementations available in many programming languages
  • Strict logic-less templating, promoting better separation of concerns

Cons of Mustache

  • Limited functionality compared to Liquid, lacking advanced features like filters and tags
  • Less flexibility in template design due to its minimalist approach
  • Smaller community and ecosystem compared to Liquid

Code Comparison

Mustache:

{{#items}}
  <li>{{name}}: {{price}}</li>
{{/items}}

Liquid:

{% for item in items %}
  <li>{{ item.name }}: {{ item.price | currency }}</li>
{% endfor %}

Mustache uses a simpler syntax with {{#items}} for loops, while Liquid uses {% for item in items %}. Liquid also demonstrates built-in filters like currency for formatting, which are not available in Mustache's basic implementation.

Both templating engines serve different purposes: Mustache focuses on simplicity and portability, while Liquid offers more advanced features and is tightly integrated with the Shopify ecosystem. The choice between them depends on the specific requirements of your project and the level of complexity needed in your templates.

Minimal templating on steroids.

Pros of Handlebars.js

  • More flexible and extensible with custom helpers and partials
  • Better performance for complex templates due to precompilation
  • Wider ecosystem and community support beyond e-commerce

Cons of Handlebars.js

  • Steeper learning curve for beginners
  • Less built-in functionality for e-commerce specific use cases
  • Requires additional setup and configuration for advanced features

Code Comparison

Liquid:

{% if product.title == "Awesome Shoes" %}
  This product is awesome!
{% endif %}

Handlebars:

{{#if (eq product.title "Awesome Shoes")}}
  This product is awesome!
{{/if}}

Both Liquid and Handlebars.js are popular templating engines, but they cater to different use cases. Liquid is tightly integrated with Shopify's ecosystem and provides out-of-the-box functionality for e-commerce applications. It's easier to learn and use for simple templating needs.

Handlebars.js, on the other hand, offers more flexibility and extensibility, making it suitable for a wider range of applications beyond e-commerce. It provides better performance for complex templates through precompilation but requires more setup and configuration for advanced features.

The code comparison shows that both engines have similar syntax for basic conditionals, with Handlebars requiring a custom helper (eq) for equality comparison. This illustrates the trade-off between Liquid's simplicity and Handlebars' extensibility.

21,636

Pug – robust, elegant, feature rich template engine for Node.js

Pros of Pug

  • More concise syntax with significant whitespace, reducing boilerplate
  • Powerful mixins for reusable code blocks and template inheritance
  • Built-in support for JavaScript expressions and logic

Cons of Pug

  • Steeper learning curve due to unique syntax
  • Less resemblance to HTML, potentially making it harder for designers
  • Requires compilation step, unlike Liquid's runtime interpretation

Code Comparison

Pug:

ul
  each item in items
    li= item.name

Liquid:

<ul>
  {% for item in items %}
    <li>{{ item.name }}</li>
  {% endfor %}
</ul>

Pug uses indentation to define structure and a more compact syntax, while Liquid maintains HTML-like tags and uses special delimiters for logic. Pug's syntax is more concise but may be less intuitive for those familiar with HTML. Liquid's syntax is closer to traditional templating languages and may be easier for beginners to grasp.

Both templating engines are powerful and widely used, with Liquid being particularly popular in e-commerce platforms like Shopify, while Pug is often favored in Node.js environments for its JavaScript integration and expressive syntax.

3,758

HTML Abstraction Markup Language - A Markup Haiku

Pros of Haml

  • More concise syntax, reducing the amount of code needed
  • Enforces clean, indentation-based structure
  • Supports inline Ruby code execution

Cons of Haml

  • Steeper learning curve for developers new to the syntax
  • Less flexibility in formatting compared to HTML-like templates
  • Limited adoption outside of Ruby community

Code Comparison

Haml:

%ul.menu
  - @items.each do |item|
    %li= item.name

Liquid:

<ul class="menu">
  {% for item in items %}
    <li>{{ item.name }}</li>
  {% endfor %}
</ul>

Haml uses a more compact syntax with significant whitespace, while Liquid maintains an HTML-like structure with special tags for logic. Haml allows direct Ruby code execution, whereas Liquid uses a restricted syntax for variables and control structures.

Both templating languages have their strengths, with Haml focusing on conciseness and Liquid prioritizing readability and ease of use for non-programmers. The choice between them often depends on the project requirements and team preferences.

11,931

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Pros of Slim

  • More flexible and suitable for a wider range of web applications
  • Better performance for complex routing and middleware scenarios
  • Supports PSR-7 HTTP message interfaces for improved interoperability

Cons of Slim

  • Steeper learning curve for beginners compared to Liquid's simplicity
  • Requires more setup and configuration for basic functionality
  • Less suitable for simple templating tasks in static sites or email templates

Code Comparison

Slim (PHP):

$app = new \Slim\App();
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello, " . $args['name']);
});
$app->run();

Liquid (Ruby-like syntax):

{% if user %}
  Hello {{ user.name }}!
{% else %}
  Hello, stranger!
{% endif %}

Slim is a PHP micro-framework for building web applications, while Liquid is a template language primarily used for e-commerce platforms and static site generators. Slim offers more control over application structure and routing, making it suitable for complex web applications. Liquid, on the other hand, excels in simplicity and ease of use for basic templating tasks, particularly in e-commerce contexts. The code comparison highlights the difference in approach: Slim focuses on routing and request handling, while Liquid emphasizes template rendering with simple logic.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build status Inline docs

Liquid template engine

Introduction

Liquid is a template engine which was written with very specific requirements:

  • It has to have beautiful and simple markup. Template engines which don't produce good looking markup are no fun to use.
  • It needs to be non evaling and secure. Liquid templates are made so that users can edit them. You don't want to run code on your server which your users wrote.
  • It has to be stateless. Compile and render steps have to be separate so that the expensive parsing and compiling can be done once and later on you can just render it passing in a hash with local variables and objects.

Why you should use Liquid

  • You want to allow your users to edit the appearance of your application but don't want them to run insecure code on your server.
  • You want to render templates directly from the database.
  • You like smarty (PHP) style template engines.
  • You need a template engine which does HTML just as well as emails.
  • You don't like the markup of your current templating engine.

What does it look like?

<ul id="products">
  {% for product in products %}
    <li>
      <h2>{{ product.name }}</h2>
      Only {{ product.price | price }}

      {{ product.description | prettyprint | paragraph }}
    </li>
  {% endfor %}
</ul>

How to use Liquid

Install Liquid by adding gem 'liquid' to your gemfile.

Liquid supports a very simple API based around the Liquid::Template class. For standard use you can just pass it the content of a file and call render with a parameters hash.

@template = Liquid::Template.parse("hi {{name}}") # Parses and compiles the template
@template.render('name' => 'tobi')                # => "hi tobi"

Concept of Environments

In Liquid, a "Environment" is a scoped environment that encapsulates custom tags, filters, and other configurations. This allows you to define and isolate different sets of functionality for different contexts, avoiding global overrides that can lead to conflicts and unexpected behavior.

By using environments, you can:

  1. Encapsulate Logic: Keep the logic for different parts of your application separate.
  2. Avoid Conflicts: Prevent custom tags and filters from clashing with each other.
  3. Improve Maintainability: Make it easier to manage and understand the scope of customizations.
  4. Enhance Security: Limit the availability of certain tags and filters to specific contexts.

We encourage the use of Environments over globally overriding things because it promotes better software design principles such as modularity, encapsulation, and separation of concerns.

Here's an example of how you can define and use Environments in Liquid:

user_environment = Liquid::Environment.build do |environment|
  environment.register_tag("renderobj", RenderObjTag)
end

Liquid::Template.parse(<<~LIQUID, environment: user_environment)
  {% renderobj src: "path/to/model.obj" %}
LIQUID

In this example, RenderObjTag is a custom tag that is only available within the user_environment.

Similarly, you can define another environment for a different context, such as email templates:

email_environment = Liquid::Environment.build do |environment|
  environment.register_tag("unsubscribe_footer", UnsubscribeFooter)
end

Liquid::Template.parse(<<~LIQUID, environment: email_environment)
  {% unsubscribe_footer %}
LIQUID

By using Environments, you ensure that custom tags and filters are only available in the contexts where they are needed, making your Liquid templates more robust and easier to manage.

Error Modes

Setting the error mode of Liquid lets you specify how strictly you want your templates to be interpreted. Normally the parser is very lax and will accept almost anything without error. Unfortunately this can make it very hard to debug and can lead to unexpected behaviour.

Liquid also comes with a stricter parser that can be used when editing templates to give better error messages when templates are invalid. You can enable this new parser like this:

Liquid::Environment.default.error_mode = :strict
Liquid::Environment.default.error_mode = :strict # Raises a SyntaxError when invalid syntax is used
Liquid::Environment.default.error_mode = :warn # Adds strict errors to template.errors but continues as normal
Liquid::Environment.default.error_mode = :lax # The default mode, accepts almost anything.

If you want to set the error mode only on specific templates you can pass :error_mode as an option to parse:

Liquid::Template.parse(source, error_mode: :strict)

This is useful for doing things like enabling strict mode only in the theme editor.

It is recommended that you enable :strict or :warn mode on new apps to stop invalid templates from being created. It is also recommended that you use it in the template editors of existing apps to give editors better error messages.

Undefined variables and filters

By default, the renderer doesn't raise or in any other way notify you if some variables or filters are missing, i.e. not passed to the render method. You can improve this situation by passing strict_variables: true and/or strict_filters: true options to the render method. When one of these options is set to true, all errors about undefined variables and undefined filters will be stored in errors array of a Liquid::Template instance. Here are some examples:

template = Liquid::Template.parse("{{x}} {{y}} {{z.a}} {{z.b}}")
template.render({ 'x' => 1, 'z' => { 'a' => 2 } }, { strict_variables: true })
#=> '1  2 ' # when a variable is undefined, it's rendered as nil
template.errors
#=> [#<Liquid::UndefinedVariable: Liquid error: undefined variable y>, #<Liquid::UndefinedVariable: Liquid error: undefined variable b>]
template = Liquid::Template.parse("{{x | filter1 | upcase}}")
template.render({ 'x' => 'foo' }, { strict_filters: true })
#=> '' # when at least one filter in the filter chain is undefined, a whole expression is rendered as nil
template.errors
#=> [#<Liquid::UndefinedFilter: Liquid error: undefined filter filter1>]

If you want to raise on a first exception instead of pushing all of them in errors, you can use render! method:

template = Liquid::Template.parse("{{x}} {{y}}")
template.render!({ 'x' => 1}, { strict_variables: true })
#=> Liquid::UndefinedVariable: Liquid error: undefined variable y

Usage tracking

To help track usages of a feature or code path in production, we have released opt-in usage tracking. To enable this, we provide an empty Liquid:: Usage.increment method which you can customize to your needs. The feature is well suited to https://github.com/Shopify/statsd-instrument. However, the choice of implementation is up to you.

Once you have enabled usage tracking, we recommend reporting any events through Github Issues that your system may be logging. It is highly likely this event has been added to consider deprecating or improving code specific to this event, so please raise any concerns.