LoginSignup
3

More than 3 years have passed since last update.

Ruby + Mustache で Hello World

Posted at

概要

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

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

$ gem install mustache

Hello World

シンプルなサンプルコードを示す。

require 'mustache'

# 第一引数にテンプレート文字列
# 第二引数にHashオブジェクト
hello = Mustache.new.render('Hello, {{planet}}.', {planet: 'world'})
puts hello

実行結果。

Hello, world.

HTML テンプレートファイルを読み込んで値を埋め込む

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

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

<!-- mydata オブジェクトの message を出力-->
<p>{{mydata.message}}</p>

<p>
<!-- ループ -->
{{#mydata}}
  {{#list}}
    {{.}}<br>
  {{/list}}
{{/mydata}}
</p>

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

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

</body>
</html>

ソースコード。

require 'mustache'

# 第一引数にテンプレートファイル名
# 第二引数にHashオブジェクト
output = Mustache.render_file(
  'my-template-file',
  {
    :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>

参考資料

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
3