LoginSignup
1
0

More than 3 years have passed since last update.

Ruby の tilt パッケージを使って ERB テンプレートを処理する

Last updated at Posted at 2020-02-10

概要

  • Ruby の tilt パッケージを使って ERB テンプレートを処理する
  • 今回の環境: macOS Catalina + Ruby 2.7.0 + tilt 2.0.10

tilt とは

様々なテンプレートエンジンを統一して扱えるインターフェースを持ったライブラリ。

tilt | RubyGems.org | コミュニティのGemホスティングサービス

Generic interface to multiple Ruby template engines

tilt を導入することで、複数のテンプレートエンジンに対応したライブラリ (Web アプリケーションフレームワークや静的サイトジェネレーターなど) が作りやすくなる。

rtomayko/tilt: Generic interface to multiple Ruby template engines

Tilt is a thin interface over a bunch of different Ruby template engines in an attempt to make their usage as generic as possible. This is useful for web frameworks, static site generators, and other systems that support multiple template engines but don't want to code for each of them individually.

tilt パッケージのインストール

$ gem install tilt

Hello World

HTML を記述した ERB テンプレートファイルを用意。
今回は hello.erb というファイル名で保存する。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<!-- @title を出力-->
<title><%= @title %></title>

</head>
<body>

<!-- @message を出力-->
<p><%= @message %></p>

</body>
</html>

ソースコード。

require 'tilt'

# 変数を定義
@title   = 'Hello, world.'
@message = 'こんにちは、世界。'

# Tile に包まれた ERB テンプレートオブジェクト
template = Tilt.new('hello.erb')

# self が指すスコープでレンダリング
output = template.render(self)

# 結果を出力
puts output

実行結果。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<!-- @title を出力-->
<title>Hello, world.</title>

</head>
<body>

<!-- @message を出力-->
<p>こんにちは、世界。</p>

</body>
</html>

ループや条件分岐など

HTML を記述した ERB テンプレートファイルを用意。
今回は my-template.erb というファイル名で保存する。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- title を出力-->
<title><%= title %></title>
</head>
<body>

<!-- mydata オブジェクトの message を出力-->
<p><%= mydata[:message] %></p>

<p>
<!-- ループ -->
<% mydata['list'].each do |item| %>
  <%= item %><br>
<% end %>
</p>

<p>
<!-- hoge が存在する場合に出力-->
<%= 'Hoge exists.' if mydata['hoge'] %>
</p>

<p>
<!-- fuga が存在しない場合に出力-->
<%= 'Fuga does not exists.' if !mydata['fuga'] %>
</p>

</body>
</html>

ソースコード。

require 'tilt'

# Tile に包まれた ERB テンプレートオブジェクト
template = Tilt.new('my-template.erb')

# 第一引数: 他に影響されないスコープとして Object.new を指定
# 第二引数以降: テンプレートに渡す Hash オブジェクト
output = template.render(
  Object.new,
  :title => 'タイトル',
  :mydata => {
    :message => 'メッセージ',
    'list' => ['foo', 'bar', 'baz'],
    'hoge' => 'ほげ'
  })

# 結果を出力
puts output

実行結果。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- title を出力-->
<title>タイトル</title>
</head>
<body>

<!-- mydata オブジェクトの message を出力-->
<p>メッセージ</p>

<p>
<!-- ループ -->
  foo<br>
  bar<br>
  baz<br>
</p>

<p>
<!-- hoge が存在する場合に出力-->
Hoge exists.
</p>

<p>
<!-- fuga が存在しない場合に出力-->
Fuga does not exists.
</p>

</body>
</html>

参考資料

1
0
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
1
0