3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Phoenixで静的ページレンダリングする方法

Posted at

Phoenixで静的ページレンダリングする方法

Controllerからテンプレートまで、全て手動で作成する方法

routerへの追記

router.exファイルに以下の形式で記述を行う。

形式: get "/URLを記述", 省略Controller, :アクション

例として、get "/sample", SampleContoller, :homeと記述する。

この場合記述したURLでリクエストが送信されると、sample_controller.ex内のhomeというアクションが実行される。

アクションの定義

アクションは以下のように定義することができる。

def アクション(conn, params) do
  ... 
  render(conn, template_or_component)
end

アクションの引数は以下のようなものである。

  • conn - リクエスト情報が含まれている。(ここでは割愛)
  • params - URLによって渡されたパラメータがMapで格納される。

例えば/greet/:name/というルートを設定しており、/greet/taro/というURLにリクエストが送信されると、%{ "name" => "taro"}という形式でパラメタが格納される。

アクション内では必ずrender関数を実行する必要がある。

render関数

render関数の以下のように呼び出す。

形式: render(conn, template_or_component, options)

この引数の内template_or_componentが指すものはテンプレート関数コンポーネントである。

当然ながら、それを指定するためには予め定義している必要がある。

なお、テンプレート、関数コンポーネントはアプリレイアウト(もしくはルートレイアウト)の@inner_content内にレンダリングされる。

レイアウトについては、Phoenixにおけるページレンダリング順についてのメモを参照

テンプレートと関数コンポーネント

テンプレートと関数コンポーネントを作成するために、
それらを定義するHTMLモジュールとディレクトリを作成する必要がある。

まず、.*_html.ex/.*_htmlを作成する。

.*_html.exは次のように記述する。

defmodule 省略 do
  use ..., :html

  embed_templates "省略_html/*"

embed_templatesは、
テンプレートの構成を設定するために記述している。

embed_templatesで指定したディレクトリ内に、
heexファイルを配置することでテンプレートとして使用できるようになる。

例としてsample_controller.exsample_html.exを作成した場合、/sample_htmlを作成する。

sample_html.ex内にembed_templates "sample_html/*"と記述する。

関数コンポーネントの定義

関数コンポーネントは以下の例のように記述する。

def sample(assigns) do
  ~H"""
    // ここにHTMLを記述する。
    <p>function component.</p>
  """
end

テンプレート(または~Hシジル)に
次のように記述して使用する。

形式: <.関数コンポーネント名(引数) />
例: <.sample() />

なお、このモジュール内でrender関数を上書きし、
~Hシジルで表示内容を記述することもできる。

結論

以下の手順を行いテンプレートを表示させる。

  1. router.exgetでURLを記述。
  2. /controllers.*_contoller.exという名前のコントローラーファイルを生成。
  3. アクションの処理を定義する。
  4. .*_html.ex/.*_htmlを作成する。
  5. /.*_htmlにheexを配置。
  6. .*_html.exembed_templatesでディレクトリを指定する。
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?