#目的
Trotフレームワークでテンプレートのレンダリング機能を利用する。#実行環境
OS: Windows8.1Haml: ?
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Trot Framework: v0.5
#始める前に
前回の記事の続きになります。eexとhamlのテンプレートをレンダリングします。
追加もそんなにないので簡単でした。
ちょっとばかり疑問なのですが、
何故かHamlテンプレートに"!!!"のDOCTYPEを追加する記述をすると、
ArgumentErrorが発生してテンプレートがレンダリングされません。
トレースすると、Calliopeの方で何か起こっているような感じですね。
記述を消せば、実行に支障はないので気にしていませんが・・・
(Hamlのバージョンですかね・・・不明ですし)
#参考文献
https://github.com/hexedpackets/trot#目次
1. テンプレートをレンダリングするだけの簡単なお仕事##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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%html | |
%head | |
%title Haml Template | |
%body | |
%h1 Haml Template | |
%p <%= @message %> |
priv/templates/template.html.eex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>EEx Template</title> | |
</head> | |
<body> | |
<h1>EEx Template</h1> | |
<p><%= @message %></p> | |
</body> | |
</html> |
テンプレートの内容は説明をするまでもないと思いますが、
一点だけ、<%= %>でElixirのコードを埋め込んでいます。
lib/trot_sample/router.exを開き、以下の通り編集します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"
#管理人の独り言~
こういった小さい事の積み重ねで行きたいですね~ベイビーステップがいいです(笑)
まぁ、READMEにも記述があり大した内容の記事ではありませんが、
お役に立ったら嬉しいです。
Sinatraやってる時に、HamlとSlimどっちを使うかでHamlを選択しておいて良かった(笑)
Trotには、Calliope組み込まれているのでHamlを使えて嬉しいです。(個人的に記述が楽)
Calliopeとは、Elixirで使えるHamlのParserです。
Github - Calliope: https://github.com/nurugger07/calliope