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