Problem/Motivation
Story generation fails with "Render context is empty" error when components use custom Twig functions that require Drupal render context (e.g., bem(), attach_library(), drupal_settings()).
The issue occurs in the TwigStorybook library where $wrapper->render(['_story' => false]) is called during story generation without proper Drupal render context. This affects any Drupal site using component-based theming with custom Twig functions in a Drupal 11 + Storybook 9.x setup with server-side rendering.
Steps to reproduce
1. Create a component that uses a custom Twig function requiring render context
2. Create a .stories.twig file for the component
3. Run story generation: drush storybook:generate-all-stories --force
Expected result: Stories should generate successfully without errors.
Actual result: Story generation fails with error: "Render context is empty, because render() was called outside of a renderRoot() or renderInIsolation() call. Use renderInIsolation()/renderRoot() or #lazy_builder/#pre_render instead."
Proposed resolution
Wrap the TwigStorybook render calls in executeInRenderContext() within the Drupal Storybook module integration.
The solution involves:
- Injecting the RendererInterface service into the StorybookCommands class
- Wrapping generateStoriesJsonFile() calls in executeInRenderContext() with a proper RenderContext
- Using Drupal's dependency injection container to provide the renderer service
**Note**: The final implementation does not require services file modifications as the renderer service is injected through the existing create() method using $container->get('renderer'), which leverages Drupal's built-in service container.
Remaining tasks
- [x] Create patch with render context wrapper implementation
- [x] Test with components using render-context-dependent Twig functions
- [x] Verify story generation completes without errors
- [ ] Ensure compatibility across different Drupal and Storybook versions
User interface changes
None.
API changes
None. This is an internal fix that maintains existing API compatibility.
Data model changes
None.
| Comment | File | Size | Author |
|---|---|---|---|
| #6 | 3529535-fix-render-context-error-6.patch | 1.69 KB | tormi |
Issue fork storybook-3529535
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
tormiComment #3
tormiPushed the changes here: https://git.drupalcode.org/issue/storybook-3529535/-/commit/d5117a04f0d0...
Comment #4
tormiAdding the patch as well for Composer usage in projects.
Comment #6
tormiUpdated the Composer patch.
Comment #7
tormiI updated the ticket description to reflect the latest changes.
Comment #8
idiaz.ronceroJust adding here that the newer Icon API that uses
{{ icon() }}suffers from this same bug,