In the last topic, I explained how import maps work in Symfony. Now let's learn about Stimulus — a lightweight JavaScript framework that makes it easy to add interactivity to your pages without writing complex frontend code.
What is Stimulus?
Stimulus is a minimal JS framework that connects behavior to your HTML. It is ideal for:
- Adding interactivity to server-rendered pages
- Organizing JS code
- Building reusable UI components
- Gradually enhancing HTML without rewriting entire frontends
Key concept: HTML remains primary; JS enhances it where needed.
Installing the Stimulus Bundle
Step 1: Install the Bundle
composer require symfony/stimulus-bundle
Step 2: Install the Symfony Recipe Manually
php bin/console app:recipes:install symfony/stimulus-bundle
This safely applies the recipe without interfering with existing code.
What the Recipe Installs / Configures (AssetMapper)
-
Updates
importmap.phpto include@symfony/stimulus-bundleand@hotwired/stimulus. -
Creates or updates
assets/bootstrap.js:import { startStimulusApp } from '@symfony/stimulus-bundle'; const app = startStimulusApp();This initializes Stimulus on every page.
- Copies or ensures
assets/controllers/exists — your custom Stimulus controllers live here. - Creates or updates
assets/controllers.json, mapping controller names to JS files. You normally do not edit it manually.
No additional script tags are needed — AssetMapper plus import maps handle module loading.
A Simple Example of Using Stimulus
Step 1: Create a Controller File
assets/controllers/hello_controller.js:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
connect() {
console.log('Hello from Stimulus');
}
greet() {
alert('Greeting from Stimulus');
}
}
Stimulus will detect this as the hello controller.
Step 2: Attach Controller in Your Page
<div data-controller="hello">
<button data-action="click->hello#greet">Click me</button>
</div>
Step 3: Run Symfony — No Build Step Needed
With AssetMapper:
- No Webpack or Vite
- No compilation or bundling
Simply run your site, open the page and click the button — the Stimulus controller runs automatically.
Advantages Demonstrated by This Example
- Declarative Behavior: HTML attributes define JS behavior; no manual listeners required.
- Automatic Controller Initialization: Controllers in
assets/controllers/are discovered automatically. - No Build Step: Changes take effect immediately in the browser.
- Small, Focused Controllers: Each controller handles one responsibility, keeping code modular.
- Seamless Symfony Integration: Controllers initialize automatically for dynamic content.
Learn More
Read StimulusBundle: Symfony integration with Stimulus
Next Up
In the next topic, we will explore using third-party Stimulus components.