スポンサーリンク

2015年6月28日

[Elixir+Phoenix]EctoModelsの機能を使う

目的

PhoenixのEctoModels機能を把握する。

実行環境

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Phoenix Framework: v0.13.1
PostgreSQL: postgres (PostgreSQL) 9.4.4

始める前に

今までのTutorial記事の中で行っていることですが、
あまり説明もしていなかったのでまとめます。
プロジェクトの作成。
>cd プロジェクト作成ディレクトリ
>mix phoenix.new ecto_models_sample
>cd ecto_models_sample
>mix phoenix.server
>ctrl+c
準備良し。
以降、この記事でのプロジェクトと言えば、
“ecto_models_sample”を指し示す。

目次

  1. コードの自動生成
  2. 生成したモデル見る

1. コードの自動生成

コマンドはこちらにまとめてます。
[Phoenix]PhoenixとEctoのコマンドまとめ
以下のコマンドを実行して生成します。
>mix phoenix.gen.html User users name:string email:string
* creating priv/repo/migrations/20150628044017_create_user.exs
* creating web/models/user.ex
* creating test/models/user_test.exs
* creating web/controllers/user_controller.ex
* creating web/templates/user/edit.html.eex
* creating web/templates/user/form.html.eex
* creating web/templates/user/index.html.eex
* creating web/templates/user/new.html.eex
* creating web/templates/user/show.html.eex
* creating web/views/user_view.ex
* creating test/controllers/user_controller_test.exs

Add the resource to the proper scope in web/router.ex:

    resources "/users", UserController

and then update your repository by running migrations:

    $ mix ecto.migrate
色々生成されましたね。
生成後の説明に二つ指示が出ています。
  • ルーティングの追加
  • マイグレーションの実施
  • ルーティングの追加
scope "/", EctoModelsSample do
  pipe_through :browser # Use the default browser stack

  get "/", PageController, :index
  resources "/users", UserController
end
  • マイグレーションの実施
>mix ecto.create
Compiled lib/ecto_models_sample.ex
Compiled web/models/user.ex
Compiled web/router.ex
Compiled web/views/page_view.ex
Compiled web/views/layout_view.ex
Compiled lib/ecto_models_sample/endpoint.ex
Compiled web/views/error_view.ex
Compiled web/controllers/page_controller.ex
Compiled web/controllers/user_controller.ex
Compiled web/views/user_view.ex
Generated ecto_models_sample app
The database for EctoModelsSample.Repo has been created.
>mix ecto.migrate
[info] == Running EctoModelsSample.Repo.Migrations.CreateUser.change/0 forward
[info] create table users
[info] == Migrated in 0.2s
マイグレーションファイルのディレクトリ。
ディレクトリ: priv/repo/migrations/
DBを作成していないので最初にcreateしている。
やらないとエラーが出る。また二回createすると既にあるとエラーが出る。

2. 生成したモデルを見る

生成したソースコード(コントローラ)には、既にCRUD操作が記述されている。
こちらを参考にすると基本的な使い方は分かる。
またサーバを起動すると、
一通りのCRUD操作が画面上で実施できる。
こちらも合わせて実施するとより分かりやすいと思う。
実際に使っているところはコントローラを見れば良いので、
モデルモジュールについて少しやりましょう。
web/models/user.ex
defmodule EctoModelsSample.User do
  use EctoModelsSample.Web, :model

  schema "users" do
    field :name, :string
    field :email, :string

    timestamps
  end

  @required_fields ~w(name email)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If `params` are nil, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end
schemaに自分で定義していない項目がありますね。
これは関数で”timestamps/0”となります。
生成時間(inserted_at)と更新時間(updated_at)の二つの項目になります。
(また、DB内にはidの項目が自動で定義されています)
次は以下二つの記述を見ます。
@required_fields: 必須になるフィールドを記述。
@optional_fields: オプションのフィールドを記述。
以下の関数はそのままですね。
def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
end
パラメータを必須とオプションのフィールドに分離しています。
実際に使っている部分を見ればもう少し分かりやすいと思います。

管理人の独り言~

生成とマイグレーション、CRUD操作はこれで問題ないですね。
もっと詳しく見たい場合、本家のガイド見るのが一番です。
次はValidation(検証)の記事上げますね。

参考文献

​

[Phoenix]PhoenixとEctoのコマンドまとめ

目的

PhoenixとEctoのコマンドについて把握する。

実行環境

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Phoenix Framework: v0.13.1
PostgreSQL: postgres (PostgreSQL) 9.4.4

始める前に

今までのTutorial記事の中で行っていることですが、
あまり説明もしていなかったのでまとめます。

コマンドは既存のプロジェクト内で実施して下さい。

目次

  1. Phoenixのコマンドを知る
  2. Ectoのコマンドを知る

1. Phoenixのコマンドを知る

さて、自動生成コマンドを使う前にPhoenix-Frameworkのコマンドを見てみよう。
(自動生成コマンドも入っている)
Phoenixのコマンドを見るには、
以下のコマンドを実行して下さい。
>mix help | grep phoenix
mix phoenix.digest      # Digests and compress static files
mix phoenix.gen.channel # Generates a Phoenix channel
mix phoenix.gen.html    # Generates controller, model and views for an HTML-based resource
mix phoenix.gen.json    # Generates a controller and model for an JSON-based resource
mix phoenix.gen.model   # Generates an Ecto model
mix phoenix.new         # Create a new Phoenix v0.13.1 application
mix phoenix.routes      # Prints all routes
mix phoenix.server      # Starts applications and their servers
よく使うコマンドをまとめる。
new: 新しくPhoenixのプロジェクトを作成する時に使う。
routes: ルーティングの一覧を表示する。
server: Phoenixの実行。もしくはサーバ起動でもいい。
gen.html: モデル、ビュー、コントロール、テンプレート、マイグレーションのファイルを生成する。
gen.model: モデル、マイグレーションのファイルを生成する。
こんなところかな?
他のは使ったことがないから分からない。
(説明の通りだろうけど・・・)

2. Ectoのコマンドを知る

Ectoのコマンドを見るには、
以下のコマンドを実行して下さい。
>mix help | grep ecto
mix ecto.create         # Create the storage for the repo
mix ecto.drop           # Drop the storage for the repo
mix ecto.gen.migration  # Generate a new migration for the repo
mix ecto.gen.repo       # Generate a new repository
mix ecto.migrate        # Run migrations up on a repo
mix ecto.rollback       # Rollback migrations from a repo
簡単にまとめた。
create: DB生成(?)のために最初に実施する。
drop: DBを削除するために実施する。
gen.migration: マイグレーションファイルを生成する。
gen.repo: リポジトリを生成する。
migrate: マイグレーションの実施。
rollback: DBの処理と同じで処理を戻せる。
※エラーが起こった場合、DB(ログ)も確認する

管理人の独り言~

大体、PhoenixのGuide見れば載っています。

なんだろう・・・いまいちマークダウンの調子が良くない・・・
`コード`を表示しようとすると上手く文字色が出ないな。

参考文献

​

昨日、英語で@tweetが来たのだが・・・

目的

あるニュースの紹介。
広報目的の記事です。

実行環境

OS: Windows8.1

始める前に

ある(海外)ニュースレターに記事が載ったので~
(ようは、ただの雑記)

目次

  1. 昨日、英語で@tweetが来たのだが・・・

1. 昨日、英語で@tweetが来たのだが・・・

びっくりした・・・いきなり夜中に来るんだもん。
Thanks toとかって書いてあったから何やったけ?ってなりました。

翻訳してみると、
記事載っけさせてもらったぜ!ありがとな!って書いてある。

リンク先に飛んで記事を見てみた。
Functional Elixir - テクノロジー・IT

えっ!?
あの・・・他の記事が、”Elixir Conf”、”Elixir Fountain”、”Elixir |> BDD”、”Phoenixの開発者”・・・( ゚д゚)ポカーン ・・・

えっ!?
掲載して頂けたのは嬉しいのですが!
場違いなんですけど私の記事・・・

しかも、掲載されてる記事が”[espec_phoenix]Phoenixでもテストがしたい!!(導入失敗編)“この記事か・・・

管理人の独り言~

そんなわけで世界に恥を晒した感じがして、ちょっと悶絶しているので記事にしてみた。

嬉しいような、恥ずかしいような・・・
いずれにせよ記事を紹介して頂いたのは何気に初めてのことなので嬉しいでいいか!
自分の中ではあまり良い記事ではないけどよかったら読んでみて下さい。(宣伝)

海外に紹介されても恥ずかしくない記事を作成&技術力を身につけなくては!!
っと奮起するに至ったのであった・・・

以上、駄文ですが失礼しました。

参考文献

​

2015年6月27日

Markdown Hereをインストールしたのでテスト

目的

私が利用頻度の高そうなものを練習がてら記述する。

始める前に

Markdown Here: Chromeの拡張機能

目次

  1. ヘッダー
  2. 協調と打消し線
  3. リスト
  4. リンク
  5. 画像
  6. コードとシンタックスのハイライト
  7. テーブル
  8. ブロック

1. ヘッダー

#ヘッダー1
##ヘッダー2
###ヘッダー3
####ヘッダー4
#####ヘッダー5
######ヘッダー6

ヘッダー1
======
ヘッダー2
------

ヘッダー1

ヘッダー2

ヘッダー3

ヘッダー4

ヘッダー5
ヘッダー6

ヘッダー1

ヘッダー2


2. 協調と打消し線

*asterisks* or _underscores_
**asterisks** or __underscores__
**asterisks** or __underscores__
~~Scratch this.~~

asterisks or underscores
asterisks or underscores
asterisks or underscores
Scratch this.

3. リスト

1. hoge
2. huge
 * sub_list
3. foo
 1. sub_list
4. bar

* aaa
- bbb
+ ccc

  1. hoge
  2. huge
    • sub_list
  3. foo
    1. sub_list
  4. bar
  • aaa
  • bbb
  • ccc

4. リンク

[google](http://www.google.com)


5. 画像

![alt text](https://www.url.com/logo.png "Logo Title Text")

alt text

6. コードとシンタックスのハイライト

`code`

```elixir
IO.puts "text"
```

```html
<html>
</html>
```

```
code1
code2
code3
```

code
IO.puts "text"
<html>
</html>
code1
code2
code3

7. テーブル

Name | Age
--- | ---
hoge | 10
huge | 3

Name Age
hoge 10
huge 3


8. ブロック

> ブロック1
> ブロック2
> ブロック3

ブロック1
ブロック2
ブロック3


管理人の独り言~

BloggerにMarkdown言語を導入してみた。
これでQiitaやGithubのようにBloggerでもMarkdownで記事が書ける!
小さいソースコードの見辛さも改善されるのではないだろうか?
(ソースコードが大きいときはGistを使いますが・・・)
大きい文字で出そうとするとちょっと都合が良くないみたいですね。

実行のデフォルト(戻す時も同じ): ctrl+alt+m

参考文献

​

[Elixir]シンプルなsafetybox(暗号化ライブラリ)を使う

#目的

Elixirで利用できる、safetybox(暗号化ライブラリ)を使って文字を暗号化してみる。


#実行環境

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4
Safetybox: v0.1.2


#始める前に

READMEの通りに実行しただけ。


#目次

1. プロジェクト生成
2. mix.exs
3. iexから利用
4. 暗号化と認証(仮)を行うソースコード


##1. プロジェクト生成

>mix new safetybox_sample
>cd safetybox_sample
>mix test


##2. mix.exs

以下の記述を依存関係に追加。
>mix deps.get
>mix compile


##3. iexから利用

>iex -S mix
iex(1)> pwd = Safetybox.encrypt("helloworld")
"fc5e038d38a57032085441e7fe7010b0"
iex(2)> Safetybox.is_decrypted("helloelixir", pwd)
false
iex(3)> Safetybox.is_decrypted("helloworld", pwd)
true

##4. 暗号化と認証(仮)を行うソースコード

今後利用する予定があるのでサンプルを作成しておく。

>iex -S mix

iex(1)> enc_pass = SafetyboxSample.encrypt("helloworld")
"fc5e038d38a57032085441e7fe7010b0"
iex(2)> SafetyboxSample.authentication(3, "hoge", "helloworld")
false

こんな感じで利用する予定。


#管理人の独り言~

Rails Tutorial for Phoenixで暗号化を利用したいがためにやった。

本当はこちらのライブラリを使いたかったのだが、

GCCがないと駄目みたいなので・・・変更しました。
Github: Comeonin (bcryptとpbkdf2_sha512をサポートしてくれている)

しかし、すぐ使うならこちらのライブラリで十分です。

(外部公開はしないし、処理を入れたいだけ・・・ですし)

Comeoninの方はLinuxに環境を移したらですね。

bcryptサポートしてますし使い勝手が良さげ。


大した内容はないけど、プロジェクトはGithubへアップしてます。
Github: https://github.com/darui00kara/phoenix_tutorial/tree/master/safetybox_sample

#参考文献

Github - Safetybox

2015年6月26日

[Rails Tutorial for Phoenix]Filling in layout

Goal

レイアウトを作成する。

Wait a minute

今回はレイアウトを作成します。
また、カスタムCSSとBootstrapの導入も行います。
このチュートリアルでは、CSSやBootstrapの機能は利用しますが、
必要がある場合を除き、説明をする予定はありません。

Index

Filling in layout
|> Preparation
|> Custom CSS and Bootstrap
|> Layout template
|> Link and PathHelper
|> Rendering chain
|> You want to add a contact page
|> Before the end

Preparation

ブランチを切ります。

Example:

>cd path/to/sample_app
>git checkout -b filling_in_layout

Bootstrapをダウンロードし、解凍しておいて下さい。

Download: Bootstrap - Download

Custom CSS and Bootstrap

カスタムCSSとBootstrapの導入を行います。
Bootstrapの配置から行います。
Bootstrapを解凍すると以下のようなディレクトリ構成になっていると思います。

Example:

Bootstrap  
|-css  
|  |-bootstrap.css  
|  |-bootstrap.css.map  
|  |-bootstrap.min.css  
|  |-bootstrap-theme.css  
|  |-bootstrap-theme.css.map  
|  |-bootstrap-theme.min.css  
|  
|-fonts  
|  |-glyphicons-halflings-regular.eot  
|  |-glyphicons-halflings-regular.svg  
|  |-glyphicons-halflings-regular.ttf  
|  |-glyphicons-halflings-regular.woff  
|  |-glyphicons-halflings-regular.woff2  
|  
|-js  
   |-bootstrap.js  
   |-bootstrap.min.js  
   |-npm.js
配置するファイルと配置先ディレクトリは以下のとおりです。
fontsディレクトリは存在しませんので作成して下さい。

Example:

sample_app
|
priv
  |
  static  
    |
    |-css  
    |  |-bootstrap.css  
    |  |-bootstrap.css.map  
    |  
    |-fonts  
    |  |-glyphicons-halflings-regular.eot  
    |  |-glyphicons-halflings-regular.svg  
    |  |-glyphicons-halflings-regular.ttf  
    |  |-glyphicons-halflings-regular.woff  
    |  |-glyphicons-halflings-regular.woff2  
    |  
    |-js  
       |-bootstrap.js
これで配置完了です。
続いて、カスタムCSSを作成します。
(少し長いです。)

File: priv/static/css/custom.css

@import "bootstrap.css";

/* universal */
html {
  overflow-y: scroll;
}

body {
  padding-top: 60px;
}

section {
  overflow: auto;
}

textarea {
  resize: vertical;
}

.center {
  text-align: center;
}

.center h1 {
  margin-bottom: 10px;
}

/* typography */
h1, h2, h3, h4, h5, h6 {
  line-height: 1;
}

h1 {
  font-size: 3em;
  letter-spacing: -2px;
  margin-bottom: 30px;
  text-align: center;
}

h2 {
  font-size: 1.2em;
  letter-spacing: -1px;
  margin-bottom: 30px;
  text-align: center;
  font-weight: normal;
  color: #777777;
}

p {
  font-size: 1.1em;
  line-height: 1.7em;
}
ファイルの読み込みは、この次に行います。

Layout template

デフォルトのレイアウトをカスタマイズします。
しかし、その前に少しだけ説明を入れさせて下さい。
Phoenix-Frameworkのレイアウトについてです。
“mix phoenix.new”で生成したプロジェクトには、既にレイアウトが用意されています。
全テンプレートにこのレイアウトが適応されます。
つまり、レイアウトテンプレートを変更すれば全テンプレートのレイアウトが変更されるわけですね。
レイアウトを扱っているファイルは以下になります。
  • web/templates/layout/app.html.eex
  • web/views/layout_view.ex
それでは、レイアウトテンプレートを変更しましょう。
BootstrapやカスタムCSSの読み込みもここで行います。
また、動的なデザインを利用するためにjqueryの読み込みも行っています。
以下のように変更して下さい。

File: web/templates/layout/app.html.eex

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sample App!</title>
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/app.css") %>">
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/bootstrap.css") %>">
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/custom.css") %>">

    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
  </head>

  <body>
    <header class="navbar navbar-inverse">
      <div class="navbar-inner">
        <div class="container">
          <a class="logo" href="<%= page_path(@conn, :index) %>"></a>
          <nav>
            <ul class="nav nav-pills pull-right">
              <li><a href="<%= static_pages_path(@conn, :home) %>">Home</a></li>
              <li><a href="<%= static_pages_path(@conn, :help) %>">Help</a></li>
              <li><a href="<%= static_pages_path(@conn, :about) %>">About</a></li>
              <li><a href=#>Sign in</a></li>
              <li><a href="http://www.phoenixframework.org/docs">Phoenix Get Started</a>
            </ul>
          </nav>
        </div> <!-- container -->
      </div> <!-- navbar-inner -->
    </header>

    <div class="container">

      <h2>
        <p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
        <p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>
      </h2>

      <%= @inner %>

    </div> <!-- /container -->

    <script src="<%= static_path(@conn, "/js/app.js") %>"></script>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="<%= static_path(@conn, "/js/bootstrap.js") %>"></script>
  </body>
</html>
レイアウトが変わったのか確認してみましょう。

Example:

>mix phoenix.server
以下のアドレスへアクセスしてみましょう。

URL: http://localhost:4000/home

レイアウトに記述した各要素を、一つ一つ説明していきます。
CSSの読み込みを追加しています。

Example:

<link rel="stylesheet" href="<%= static_path(@conn, "/css/bootstrap.css") %>">
<link rel="stylesheet" href="<%= static_path(@conn, "/css/custom.css") %>">
static_path/2はPathHelperと呼ばれる機能を使ってパスを取得しています。
このstatic_path/2は静的ファイルへのパスを取得しています。(…/priv/static/)
IE9未満に対応するために記述しています。
魔法の言葉のようなものなので、深くは考えなくてよいです。

Example:

<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
ヘッダー部分になります。
classに記述している部分は、Bootstrapの機能を利用しています。

Example:

<header class="navbar navbar-inverse">
  <div class="navbar-inner">
    <div class="container">
      <a class="logo" href="<%= page_path(@conn, :index) %>"></a>
      <nav>
        <ul class="nav nav-pills pull-right">
          <li><a href="<%= static_pages_path(@conn, :home) %>">Home</a></li>
          <li><a href="<%= static_pages_path(@conn, :help) %>">Help</a></li>
          <li><a href="<%= static_pages_path(@conn, :about) %>">About</a></li>
          <li><a href=#>Sign in</a></li>
          <li><a href="http://www.phoenixframework.org/docs">Phoenix Get Started</a>
        </ul>
      </nav>
    </div> <!-- container -->
  </div> <!-- navbar-inner -->
</header>
static_pages_path/2については次に説明します。
テンプレートの埋め込みを行っている部分です。

Example:

<%= @inner %>
先ほど、レイアウトテンプレートの説明をしました。
全テンプレートに適応される言いましたが、こういうことです。
レイアウトテンプレートのこの部分に各テンプレートの内容が埋め込まれるため、
レイアウトテンプレートを変更すると、全テンプレートに適応されます。
javascriptの読み込みを追加しています。

Example:

<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="<%= static_path(@conn, "/js/bootstrap.js") %>"></script>
次は、リンクとPathHelperの説明をします。
リンクとPathHelperについて説明します。
先ほどのこの記述についてです。

Example:

<%= static_pages_path(@conn, :home) %>
これを説明するには二つの要素を説明する必要があります。
<%= ~ %>とstatic_pages_path/2です。
まず、<%= ~ %>について。
この記述は、eexテンプレートに対してElixirコードを埋め込むことできます。
例えば、eexテンプレートでif記述を使いたい時…

Example:

<%= if true do %>
  <p>trueだよ</p>
<% else %>
  <p>falseだよ</p>>
<% end %>
といったように、Elixirコードを使うことができるわけですね。
static_pagesで使った<%= @message %>も同じことです。
static_pages_path/2の説明をします。
これはPathHelperの機能です。
ルーティングを設定すると、そのルーティングのパスを取得できる関数を生成しています。
内部はマクロで作られています。
以下のように、ルーティングの内容を出力するコマンドがありましたね。

Example:

>mix phoenix.routes
...
static_pages_path  GET     /home                SampleApp.StaticPagesController :home
static_pages_path  GET     /help                SampleApp.StaticPagesController :help
この左側にstatic_pages_pathとあります。
これが関数名となっています。
また引数の要素ですが…
第一引数の@connは、Plug.Connのことです。毎回指定するので魔法の言葉と思って下さい。
Plugの説明をすると、それだけで終わってしまいます。
第二引数の:homeは、アクション名です。
これにより、static_pages_pathの:homeアクションのパスを寄越せ!と書いているわけですね。
以下の記述ですが、Phoenix_HTMLライブラリの機能を使って記述することができます。
Phoenix-Frameworkは幾つかのライブラリで構成されています。
Phoenix_HTMLは、その内の一つです。
aタグを使ったリンクの作成。

Example:

<li><a href="<%= static_pages_path(@conn, :home) %>">Home</a></li>
link/2を使ったリンクの作成。

Example:

<li><%= link "Home", to: static_pages_path(@conn, :home) %></li>
こちらの方が記述的に分かりやすいですね。

Rendering chain

レイアウトのヘッダー、フッダー、IE9未満の部分を別テンプレートに記述し、
そのテンプレートを呼び出してレンダリングする方法を説明します。
これは、レンダリングチェーンと呼ばれる機能で、テンプレートからテンプレートを呼び出すことができる機能です。
Ruby on Railsのパーシャルみたいなものです。
レイアウトテンプレートを以下のように変更して下さい。

File: web/templates/layout/app.html.eex

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Sample App!!</title>
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/app.css") %>">
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/bootstrap.css") %>">
    <link rel="stylesheet" href="<%= static_path(@conn, "/css/custom.css") %>">

    <%= render "shim.html" %>
  </head>

  <body>
    <%= render "header.html", conn: @conn %>

    <div class="container">
      <h2>
        <p class="alert alert-info" role="alert" style="text-align: center;"><%= get_flash(@conn, :info) %></p>
        <p class="alert alert-danger" role="alert" style="text-align: center;"><%= get_flash(@conn, :error) %></p>
      </h2>

      <%= @inner %>

      <%= render "footer.html", conn: @conn %>
    </div>

    <script src="<%= static_path(@conn, "/js/app.js") %>"></script>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="<%= static_path(@conn, "/js/bootstrap.js") %>"></script>
  </body>
</html>
大分すっきりして見やすくなりましたね。
別テンプレートを呼び出す方法ですが、以下のようにして呼び出すことができます。

Example:

<%= render "テンプレート名", 引数 %>
今回であれば、以下の部分ですね。

Example:

<%= render "shim.html" %>
<%= render "header.html", conn: @conn %>
<%= render "footer.html", conn: @conn %>
それでは、IE9未満対応、ヘッダー、フッターの各テンプレートを作成していきましょう!
まずは、IE9未満に対応するためのテンプレートを作成します。

File: web/templates/layout/shim.html.eex

<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
次に、ヘッダー部分となるテンプレートを作成します。
このテンプレートには、各主要ページへのリンクを追加していく予定です。

File: web/templates/layout/header.html.eex

<header class="navbar navbar-inverse">
  <div class="navbar-inner">
    <div class="container">
      <a class="logo" href="<%= page_path(@conn, :index) %>"></a>
      <nav>
        <ul class="nav nav-pills pull-right">
          <li><%= link "Home", to: static_pages_path(@conn, :home) %></li>
          <li><%= link "Help", to: static_pages_path(@conn, :help) %></li>
          <li><a href=#>Sign in</a></li>
        </ul>
      </nav>
    </div> <!-- container -->
  </div> <!-- navbar-inner -->
</header>
最後に、フッダー部分のテンプレートを作成します。
<footer class="footer">
  <nav>
    <ul>
      <li><%= link "About", to: static_pages_path(@conn, :about) %></li>
      <li><a href="http://www.phoenixframework.org/docs">Phoenix Get Started</a></li>
    </ul>
  </nav>
</footer>
ヘッダー、フッターのためのCSSを追加します。
カスタムCSSに以下を追加して下さい。

File: priv/static/css/custom.css

/* header */
#logo {
  float: left;
  margin-right: 10px;
  font-size: 1.7em;
  color: white;
  text-transform: uppercase;
  letter-spacing: -1px;
  padding-top: 9px;
  font-weight: bold;
  line-height: 1;
}

#logo:hover {
  color: white;
  text-decoration: none;
}

/* footer */
footer {
  margin-top: 45px;
  padding-top: 5px;
  border-top: 1px solid #eaeaea;
  color: #777777;
}

footer a {
  color: #555555;
}

footer a:hover {
  color: #222222;
}

footer small {
  float: left;
}

footer ul {
  float: right;
  list-style: none;
}

footer ul li {
  float: left;
  margin-left: 10px;
}
レイアウトの変化を確認しましょう。

Example:

>mix phoenix.server
以下のアドレスへアクセスしてみましょう。

URL: http://localhost:4000/home

You want to add a contact page

ページ追加の復習を兼ねて、contactページの追加を行います。
contactページのためのルーティングを追加します。

File: web/router.ex

scope "/", SampleApp do
  pipe_through :browser # Use the default browser stack
  ...

  get "/contact", StaticPagesController, :contact
end
StaticPagesコントローラへcontactアクション用の関数を追加します。

File: web/controllers/static_pages_controller.ex

def contact(conn, _params) do
  render conn, "contact.html"
end
contactページの内容は、お好きなように連絡先を作って下さい。
ここで作成するテンプレートでは、内容は特に作りません。
テンプレートの内容は以下の通り。

File: web/templates/static_pages/contact.html.eex

<div class="jumbotron">
  <h1>Contact</h1>
</div>
フッターへcontactページへのリンクを追加します。
<footer class="footer">
  <nav>
    <ul>
      <li><%= link "About", to: static_pages_path(@conn, :about) %></li>
      <li><%= link "Contact", to: static_pages_path(@conn, :contact) %></li>
      <li><a href="http://www.phoenixframework.org/docs">Phoenix Get Started</a></li>
    </ul>
  </nav>
</footer>
contactページの確認とフッターへcontactリンクが追加されているか確認します。

Example:

>mix phoenix.server
以下のアドレスへアクセスしてみましょう。

URL: http://localhost:4000/contact

Modify home template

homeテンプレートへサインアップをするための仮リンクの追加を行います。
サインアップを実装する時のための、ちょっとした仕込みです。

File: web/templates/static_pages/home.html.eex

<div class="jumbotron">
  <h1>Welcom to the Sample App</h1>

  <h2>
    This application is
    <a href="http://railstutorial.jp/">Ruby on Rails Tutorial</a>
    for Phoenix sample application.
  </h2>

  <a href="#" class="btn btn-large btn-primary">Sign up now!</a>
</div>
@messageはhomeアクションで不要となったので、削除します。

File: web/controllers/static_pages_controller.ex

def home(conn, _params) do
  render conn, "home.html"
end
homeページにサインアップのボタンが追加されているか確認します。

Example:

>mix phoenix.server
以下のアドレスへアクセスしてみましょう。

URL: http://localhost:4000/home

Before the end

ソースコードをマージします。
>git add .
>git commit -am "Finish filling_in_layout."
>git checkout master
>git merge filling_in_layout

Speaking to oneself

レイアウト、カスタムCSS、Bootstrap、リンク、名前付きルート…etc、色々と新しい内容が出てきましたね。
頭の中が少し、混乱しますね。
カスタムCSSは、必要になったら徐々に追記していきます。
リンク、名前付きルートはこの後でも頻繁に出てきます。
混乱してしまっている方は、気にせず先に進みましょう。
足踏みしたり座り込むより、歩きながら走りながら思考しましょう。
大丈夫、慣れれば特別なことなんて何もありません。
その内、見直してみると理解できていますよ。(多分)

Bibliography

​

人気の投稿