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.

Issue fork storybook-3529535

Command icon 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

tormi created an issue. See original summary.

tormi’s picture

Issue summary: View changes
tormi’s picture

Status: Active » Needs review
tormi’s picture

Issue summary: View changes
StatusFileSize
new2.25 KB

Adding the patch as well for Composer usage in projects.

tormi’s picture

StatusFileSize
new1.69 KB

Updated the Composer patch.

tormi’s picture

Issue summary: View changes

I updated the ticket description to reflect the latest changes.

idiaz.roncero’s picture

Just adding here that the newer Icon API that uses {{ icon() }} suffers from this same bug,