LoginSignup
3
3

More than 5 years have passed since last update.

[Elixir+Trot]テンプレートをレンダリングするだけの簡単なお仕事

Last updated at Posted at 2015-06-17

目的

Trotフレームワークでテンプレートのレンダリング機能を利用する。

実行環境

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Trot Framework: v0.5

始める前に

前回の記事の続きになります。追記&追加する形で実施します。

eexとhamlのテンプレートをレンダリングします。
コード追加もそんなにないので簡単です。

参考文献

目次

  1. テンプレートをレンダリングするだけの簡単なお仕事
  2. まとめ

1. テンプレートをレンダリングするだけの簡単なお仕事

まずは、テンプレート用のディレクトリを作成します。

>cd プロジェクトディレクトリ
>mkdir priv
>cd priv
>mkdir templates
>cd templates

/priv/templatesディレクトリへ以下の名称の二つファイルを作成して下さい。
名称1: template.html.eex
名称2: template.html.haml

ファイルの内容は以下の通り。

priv/templates/template.html.haml

template.html.eex
<html>
  <head>
    <title>EEx Template</title>
  </head>

  <body>
    <h1>EEx Template</h1>
    <p><%= @message %></p>
  </body>
</html>

priv/templates/template.html.eex

template.html.haml
%html
    %head
        %title Haml Template

    %body
        %h1 Haml Template
        %p <%= @message %>

テンプレートの内容は説明をするまでもないと思いますが、
一点だけ、<%= %>でElixirのコードを埋め込んでいます。

lib/trot_sample/router.exを開き、以下の通り編集します。

router.ex
defmodule TrotSample.Router do
  use Trot.Router
  use Trot.Template

  get "/", do: 200

  get "/hello" do
    "Hello Trot!!"
  end

  get "/hello/haml" do
    render_template("template.html.haml", [message: "Hello Haml"])
  end

  get "/hello/eex" do
    render_template("template.html.eex", [message: "Hello EEx"])
  end

  import_routes Trot.NotFound
end

ルーティング先を定義して、render_templateでテンプレートファイルを指定しています。
第二引数には、送っているパラメータが記述されていますね。

第二引数で複数のパラメータを送るのはまだやっていないので何とも分かりません。

Tips:
@template_rootの記述を使えば、
テンプレートを置くディレクトリを変更することもできるみたいです。
例) @template_root "templates/root"

デフォルトはpriv/templatesに設定されていました。
(Trotのソースコードに記述有)

2. まとめ

TrotのREADMEに説明があり大した内容の記事ではありませんが、
お役に立ったら嬉しいです。

ちょっとばかり疑問なのですが、
何故かHamlテンプレートに"!!!"のDOCTYPEを追加する記述をすると、
ArgumentErrorが発生してテンプレートがレンダリングされません。
calliopeの方で何か起こっているのでしょうか・・・

こういった小さい事の積み重ねで行きたいですね~
ベイビーステップでいいです(笑)

3
3
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
3
3