2

For ref, I'm working on https://www.drupal.org/project/focal_point/issues/3162218

I have a twig file that handles the contents of a modal window and I want to load a particular CSS file whenever this twig file is loaded. I've added the following to the top of the .twig:

{{ attach_library('focal_point/drupal.focal_point_preview') }}

...and in my libraries.yml I have:

drupal.focal_point_preview:
  version: VERSION
  js:
      js/focal_point_preview.js: {}
  css:
    theme:
      css/focal_point_preview.css: {}

If I put the attach_library() call in another (inappropriate) template the js/css is present on the page before the modal is loaded and therefore it works properly, but this is not the correct place for these libraries to be added since they are only needed when the modal is opened.

At some point in the past this worked but as of now it definitely doesn't. Thoughts?

2 Answers 2

1

render() only works because of EarlyRenderingControllerWrapperSubscriber, which should have been removed by now:

 * In other words: this just exists to ease the transition to Drupal 8: it
 * allows controllers that return render arrays (the majority) and
 * \Drupal\Core\Ajax\AjaxResponse\AjaxResponse objects (a sizable minority that
 * often involve a fair amount of rendering) to still do early rendering. But
 * controllers that return any other kind of response are already expected to
 * do the right thing, so if early rendering is detected in such a case, an
 * exception is thrown.
 *
 * @see \Drupal\Core\Render\RendererInterface
 * @see \Drupal\Core\Render\Renderer
 *
 * @todo Remove in Drupal 9.0.0, by disallowing early rendering.

So don't use any render method. Ajax renders HTML content automatically and so makes sure to catch all metadata which bubbles up.

BTW in a module handling AJAX responses you don't need to bubble up attachments through Twig:

{{ attach_library('focal_point/drupal.focal_point_preview') }}

You can add them directly to the Ajax response:

$response->addAttachments(['library' => ['focal_point/drupal.focal_point_preview']]);
0

My issue was caused by using renderPlain() instead of render()

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.