大家好下面Drupal 8 EventSubscriber类应该将drupalSettings附加到Drupal 8 javascript设置中。但不幸的是这个\ Drupal :: service('渲染器') - > renderRoot($ js_data);没有附加drupal javascript设置。
namespace Drupal\ejectorseat\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Url;
class EjectorseatSubscriber implements EventSubscriberInterface {
public function customEjector(GetResponseEvent $event) {
$account = \Drupal::currentUser();
$ejectorseat_interval = \Drupal::config('ejectorseat.settings')->get('ejectorseat_interval');
if(empty($ejectorseat_interval)){
$ejectorseat_interval = 60;
}
$ejectorseat_background = \Drupal::config('ejectorseat.settings')->get('ejectorseat_background');
if(empty($ejectorseat_background)){
$ejectorseat_background = 0;
}
if ($account->id() > 0 && (int) $ejectorseat_interval) {
$js_data = array();
$js_data['#attached']['drupalSettings']['ejectorSeat']['interval'] = $ejectorseat_interval;
$js_data['#attached']['drupalSettings']['ejectorSeat']['url'] = Url::fromRoute('ejectorseat/check');
$js_data['#attached']['drupalSettings']['ejectorSeat']['ignoreFocus'] = $ejectorseat_background ? TRUE : FALSE;
\Drupal::service('renderer')->renderRoot($js_data);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('customEjector');
return $events;
}
}
答案 0 :(得分:0)
我遇到了同样的问题,我没有找到OOP解决方案。 在您的情况下,只需将您的逻辑形式的customEjector方法放在 ejectorseat.module 文件中名为 hook_js_settings_alter 的HOOK中。通过这种方式,您可以确保drupalSettings对象中的所有变量都可用。
仅供演示:
<?php
/**
* Implements hook_js_settings_alter().
*
*/
function ejectorseat_js_settings_alter(array &$settings,
\Drupal\Core\Asset\AttachedAssetsInterface $assets
) {
...
$settings['all_settings'] = $globalSettings->getAll();
//if you want to push only a single value
$settings['custom_link'] = $globalSettings->get('custom_link')
$settings['ejectorSeat']['interval'] = $ejectorseat_interval;
$settings['ejectorSeat']['url'] = Url::fromRoute('ejectorseat/check');
$settings['ejectorSeat']['ejectorSeat']['ignoreFocus'] = $ejectorseat_background ? TRUE : FALSE;
}