LoginSignup
25
17

More than 5 years have passed since last update.

Rails with Liquid

Last updated at Posted at 2014-04-10

LiquidRubyで記述されたテンプレートエンジンです。
ShopifyJekyllなどで利用されています。

LiquidはERBとは違い、独自のレキサーとパーサーで解析をするので
エンドユーザーにテンプレートの編集機能を安全に提供できます。
(ShopifyではEmail Templatesで利用されています。)

Example

Railsでの簡単な使い方を紹介します。
(Liquid DesignersLiquid Outputが参考になりました。)

Gemfile

Gemliquidを追加します。

gem 'liquid'

Models

Modelliquid_methodsにテンプレートで利用するキーワードを追加します。

product

liquid_methodsに指定したキーワードのみがテンプレートで利用できます。(安心ですね!)

class Product < ActiveRecord::Base
  liquid_methods :title, :vendor, :variants
  has_many :variants
end

variant

ProductVariantは1対多の関係です。(Railsではおなじみですね!)

class Variant < ActiveRecord::Base
  liquid_methods :title, :price
  belongs_to :product
end

Controllers & Views

GET /catalogsでヒアドキュメントのテンプレートがレンダリングされます。
(オリジナルのExample snippetを参考にしています。)

class CatalogsController < ApplicationController
  before_action :set_products, only: [:index]

  def index
    render text: Liquid::Template.parse(template).render('products' => @products).html_safe
  end

  private
    def set_products
      @products = Product.all
    end

    def template
      <<-EOS
      <ul id="products">
        {% for product in products %}
          <li>
            <h2>{{ product.title }}</h2>
            <ul>
              {% for variant in product.variants %}
                <li>
                  <h3>{{ variant.title }}</h3>
                  Only {{ variant.price | format_as_money }}
              {% endfor %}
            </ul>
          </li>
        {% endfor %}
      </ul>
      EOS
    end
end

コードはGitHubに公開しています。

Tips

Editor

Sublime TextにはパッケージのLiquid Syntaxでシンタックスハイライトが利用できます。

25
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
17