liquid README

The project's README from github.com/Shopify/liquid. As one markdown file: README.md.

Build status Inline docs

Liquid template engine

Introduction

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

Why you should use Liquid

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. For smaller projects, a global environment is available via Liquid::Environment.default.

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 different parsers 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 = :strict2 # Raises a SyntaxError when invalid syntax is used in all tags
Liquid::Environment.default.error_mode = :strict  # Raises a SyntaxError when invalid syntax is used in some tags
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.

liquid (Shopify/liquid)

Searching Database…

11.9K ·GitHub
这是什么?Liquid 是 Shopify 开发的模板引擎,可以把动态内容嵌入 HTML、邮件或其他文本中,同时确保对不可信的、由用户编写的模板保持安全。
它是框架还是库?它是一个嵌入到应用中的 Ruby gem(库),核心是 Liquid::Template 类,你可以用它来编译和渲染模板。
怎么把它添加到项目中?在 Gemfile 中添加 gem 'liquid',然后把模板内容传给 Liquid::Template,并调用 render 方法,传入一个包含变量的 hash。
使用它之前需要准备什么?只需要 Ruby 和 Liquid gem,它没有列出任何外部依赖。
默认情况下它会严格检查我的模板吗?不会,默认的解析器比较宽松,几乎什么都能通过而不报错,这会让调试变得困难;如需更好的校验,你需要主动启用 :strict 或 :warn 错误模式。
为什么要用 Liquid,而不是直接 eval 模板代码?Liquid 从不执行(eval)模板代码,因此它的设计让最终用户可以编辑模板,而无法在你的服务器上运行任意代码。
Liquid 中的 Environment 是什么?Environment 是一个有作用域的容器,用于存放自定义标签、过滤器和配置,让你能在不同上下文之间隔离功能(例如用户主题与邮件模板),而不必依赖全局覆盖。
能让 Liquid 在遇到缺失的变量时报错,而不是默默忽略吗?可以,给 render 传入 strictvariables: true 和/或 strictfilters: true,或者使用 render!,这样遇到第一个未定义的变量或过滤器错误时就会抛出异常。
用量追踪功能是做什么用的?这是一个需主动开启的 Liquid::Usage.increment 钩子,你可以自定义它来记录生产环境中特定功能或代码路径的使用情况,便于追踪已弃用的功能。
Which topics is it in?markup, ruby, template, security, library, web, mit, open-source
Creator
Shopify
Size
6.4 MB
Stars
11.9K
Age
18y
Commits · 90 Days