Hotwire Discussion

Controllers organisation


Can we organise controllers inside sub folders :slight_smile:

  • controllers
    • sub_dir_1
      • first_controller.js
      • second_controller_2.js
    • sub_dir_2
      • third_controller.js

Thanks in advance

1 Like

Do you want your subdirectories to namespace the controllers? So if you had, say, a controller at posts/list_controller.js, would you want to refer to it in your markup as posts-lists-controller or lists-controller?

If you want lists-controller, that’s quite easy if you’re using webpack. You presumably have a line somewhere like this (you get this by default if you use webpacker on a rails project):

const context = require.context("controllers", true, /_controller\.js$/)

That second argument — true — tells webpack to include subdirectories.

If you want controllers to be namespaced (posts-list-controller), I’m sure that’s possible, just not sure how off-hand. You’ll probably need to look into webpack config or something.



You can call the controller like this:
sub_dir_1–first or sub_dir_2–third

Just add – between folders: