3
2

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はv1.6系v1.7系でページの追加方法が違うため注意が必要。

v1.6系

新しいページを追加するために作業する必要があるファイルは以下のとおりです。

  • router.exs
    • get "/hello", HelloController, :indexを追加
  • controllers/hello_controller.exを作成し以下に追記
  • MyappWebMyappのところはプロジェクト名により変わるため注意
defmodule MyappWeb.HelloController do 
	use MyappWeb, :controller 
	
	def index(conn, _params) do 
		render(conn, "index.html") 
	end 
end
  • views/hello_view.ex

MyappWebMyappのところはプロジェクト名により変わるため注意

defmodule MyappWeb.HelloView do 
	use MyappWeb, :view
end
  • templates/hello/index.html.heex
  • 初期状態ではhelloディレクトリはないはずなので作成する
  • 以下を記述
<div class="phx-hero"> 
	<h2>Hello World, from Phoenix!</h2> 
</div>

1.7系

アプリ名_web/router.exに新しいルートを追加

scope "/", Phoenix177Web do
	pipe_through :browser

	get "/", PageController, :home
	get "/hello", HelloController, :index #<- new
end

アプリ名_web/controllers直下にhello_controller.exを作成

defmodule ${アプリ名}Web.HelloController do
  use ${アプリ名}Web, :controller

  def index(conn, _params) do
    render(conn, :index)
  end
end

アプリ名_web/controllers直下にhello_html.exを作成

defmodule HelloWeb.HelloHTML do
  use HelloWeb, :html

	# 直接DOMを書く場合
  def index(assigns) do
    ~H"""
    Hello!
    """
  end

	# DOMを別ファイルで記述する場合
  embed_templates "hello_html/*"	
end

アプリ名_web/controllers直下にhello_htmlディレクトリを作成
アプリ名_web/controllers/hello_html直下にindex_html.heexを作成

<section>
  <h2>Hello World, from Phoenix!</h2>
</section>
3
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?