はじめに
phoniexでの処理の流れを追っていた時に○○HTMLモジュールの存在で混乱した。
そこでその理解を深めるために公式ドキュメントを引用し理解を補完する。
概要
最初の理解はこうだった
localhost:4000/hogehogeにアクセスをする
router.exからhogehogeのルーティングを確認しhogehoge_controller.exへアクセスをする
router.exに書かれていた
get "/hogehoge", hogehogeController, :index
からdef indexの処理が呼び出される
index.html.heexが呼び出されその内容が処理される
公式ドキュメント抜粋
公式ドキュメントを読み込むと以下のように記載があった。
In order for the render/3 function to work correctly, the controller and view must share the same root name (in this case Hello), and the HelloHTML module must include an embed_templates definition specifying where its templates live. By default the controller, view module, and templates are collocated together in the same controller directory. In other words, HelloController requires HelloHTML, and HelloHTML requires the existence of the lib/hello_web/controllers/hello_html/ directory, which must contain the show.html.heex template.
render/3 関数が正しく動作するためには、コントローラとビューが同じルート名 (この場合は Hello) を共有している必要があり、HelloHTML モジュールには、テンプレートの格納場所を指定する embed_templates 定義が含まれている必要があります。デフォルトでは、コントローラ、ビューモジュール、およびテンプレートは同じコントローラディレクトリに配置されます。つまり、HelloController は HelloHTML を必要とし、HelloHTML は lib/hello_web/controllers/hello_html/ ディレクトリの存在を必要とし、このディレクトリには show.html.heex テンプレートが含まれている必要があります。
HelloController は HelloHTML を必要とし、HelloHTML は lib/hello_web/controllers/hello_html/ ディレクトリの存在を必要とし、このディレクトリには show.html.heex テンプレートが含まれている必要があります。
まとめ
つまり、コントローラー(.ex)はテンプレート(.heex)を直接呼び出しているのではなく、間にある**「HTMLモジュール(.ex)」**を呼び出しています。
そして、これらが正しく動くためには、Phoenixの強力な**命名規則(規約)**に従って、
HogehogeController (コントローラー)
HogehogeHTML (HTMLモジュール)
lib/app_web/controllers/hogehoge_html/ (テンプレート用ディレクトリ)
の3つの「ルート名(この場合は Hogehoge)」をきっちり一致させて配置する必要がある、ということが分かりました。
終わりに
まとめに関してはAIからのレビューを受けた
参考資料