{"title":"Controllers","description":"Route Amber V2 requests through controller actions and ECR views","section":"guides","version":"v2","path":"guides/controllers","canonical_url":"https://amberframework.org/docs/v2/guides/controllers","markdown_url":"https://amberframework.org/docs/v2/guides/controllers.md","inherited":false,"content_markdown":"# Controllers\n\nA controller action turns an HTTP request into a response. Amber creates the\ncontroller selected by the router, runs its filters, calls the action, and\nfinalizes the response through the active pipeline.\n\n**Run from: the application root.**\n\n```bash\namber generate controller Posts index show\n```\n\nThe generator writes Crystal controller code and ECR views, but it deliberately\ndoes not guess routes. For the command above it creates\n`src/controllers/posts_controller.cr`, `src/views/posts/index.ecr`, and\n`src/views/posts/show.ecr`.\n\n**File: `config/routes.cr` — add these routes inside the existing\n`Amber::Server.configure` block.**\n\n```crystal\nAmber::Server.configure do\n  routes :web do\n    get \"/posts\", PostsController, :index\n    get \"/posts/:id\", PostsController, :show\n  end\nend\n```\n\n## Actions and views\n\n**File: `src/controllers/posts_controller.cr` — replace the generated action\nbodies with the application behavior. Keep the class inside this file.**\n\n```crystal\nclass PostsController < ApplicationController\n  def index\n    title = \"Recent posts\"\n    render(\"index.ecr\")\n  end\n\n  def show\n    post_id = params[:id]\n    render(\"show.ecr\")\n  end\nend\n```\n\nLocal variables remain available to the ECR template rendered by the action.\nKeep request parsing and authorization in explicit boundaries; use the [Schema\nAPI](../schema-api/index.md) when input needs typed validation.\n\nAmber's `resources` macro uses the conventional action names `index`, `new`,\n`create`, `show`, `edit`, `update`, and `destroy`. Ordinary actions may use any\nname when registered explicitly.\n\n## Controller interfaces\n\n- [Sessions and flash](sessions.md)\n- [Request and response objects](request-and-response-objects.md)\n- [Routing](../routing/index.md)\n- [Schema API](../schema-api/index.md)\n\nV2 web output is ECR. Examples that require `.slang` templates belong to the\nV1 documentation and should not be copied into a new V2 application."}