在前一章,我們創(chuàng)建了 Menu
項目?,F(xiàn)在,讓我們進入項目的根目錄,啟動服務(wù)器:
$ cd menu
$ mix phx.server
打開瀏覽器,訪問 http://localhost:4000 網(wǎng)址,我們會看到如下截圖所示的內(nèi)容:
那么,從輸入網(wǎng)址到返回頁面期間,都發(fā)生了什么?讓我們來簡單了解一下。
-
我們在瀏覽器訪問
http://localhost:4000
網(wǎng)址 -
Phoenix 在服務(wù)端收到 HTTP 請求,它檢查
menu
目錄下的lib/menu_web/router.ex
文件,定位到如下內(nèi)容:scope "/", MenuWeb do pipe_through :browser # Use the default browser stack get "/", PageController, :index end
我們看到,
router.ex
文件里已經(jīng)設(shè)定好這么一條規(guī)則:用戶get
路徑/
時,PageController
模塊中的index
動作將接手處理請求。 -
按圖索驥,我們來看看
lib/menu_web/controllers/page_controller.ex
文件內(nèi)容:defmodule MenuWeb.PageController do use MenuWeb, :controller def index(conn, _params) do render conn, "index.html" end end
目前
page_controller.ex
文件中只定義了index
一個動作 - 正是index
動作中的render conn, "index.html"
渲染了我們上面截圖中的內(nèi)容。那么,我是怎么知道
PageController
定義在lib/menu_web/controllers/page_controller.ex
文件的?你可能會這樣問。這里,我們要了解 Phoenix 的一個約定:所有的控制器都定義在controllers
目錄下,并且文件名與模塊名的命名有對應(yīng)關(guān)系:文件名是a_b.ex
時,對應(yīng)的模塊名就是AB
。 -
最后我們就來到
tempates/page/index.html
文件。
很簡單是不是?
讓我們依葫蘆畫瓢,添加一個 /help
試試。
不過,在動手前,且讓我們先在當前目錄下初始化 git,將 mix phx.new
生成的所有文件保存起來:
$ git init
$ git add .
$ git commit -m 'init`
這樣,我們后面想要清理用不到的文件時,就非常容易。
添加幫助頁面
-
首先在
router.ex
文件中添加路由:get "/help", HelpController, :index
-
然后在
controllers
目錄下新建一個help_controller.ex
文件,添加如下內(nèi)容:defmodule MenuWeb.HelpController do use MenuWeb, :controller def index(conn, _params) do render conn, "index.html" end end
-
此時的
http://localhost:4000/help
網(wǎng)址顯示:UndefinedFunctionError at GET /help function MenuWeb.HelpView.render/2 is undefined (module MenuWeb.HelpView is not available)
報錯。錯誤顯示,我們還沒有定義
MenuWeb.HelpView
視圖模塊。 -
在
views
目錄下新建help_view.ex
文件,內(nèi)容參照views/page_view.ex
文件,如下:defmodule MenuWeb.HelpView do use MenuWeb, :view end
-
再看看
http://localhost:4000/help
網(wǎng)址:Phoenix.Template.UndefinedError at GET /help Could not render "index.html" for MenuWeb.HelpView, please define a matching clause for render/2 or define a template at "lib/menu_web/templates/help". No templates were compiled for this module.
還是報錯。提示我們要在
lib/menu_web/templates/help
目錄下創(chuàng)建一個模板文件。 -
在
lib/menu_web/templates/help
目錄下新建一個index.html.eex
文件,添加如下內(nèi)容:<p>這是幫助內(nèi)容</p>
-
再看
http://localhost:4000/help
網(wǎng)址:這一次,頁面終于顯示正常。
從路由,到控制器,到視圖,到模板,每一步,一旦出錯,Phoenix 都會有完整的提示。所以哪怕我們還不清楚它們是什么,也是可以按照提示,成功添加新頁面 - 當然,最好還是要清楚 MVC 是什么,否則再容易也很難。
另外,你可能已經(jīng)發(fā)現(xiàn),Phoenix 能夠自動刷新瀏覽器中打開的頁面,不需要我們修改文件后手動刷新頁面,非常便利。
我們來簡單整理下這一章涉及的幾個概念:
更多建議: