I have a custom Twig Extension that needs to add a Javascript library ONLY when the Twig Extension is used.
Here is my modules/custom/MY_MODULE/MY_MODULE.libraries.yml
:
my-twig-extension:
version: VERSION
js:
js/myTwigExtension.js: {}
dependencies:
- core/jquery
Here is my modules/custom/MY_MODULE/js/myTwigExtension.js
(just for testing):
console.log("Hello World!!! at " + Date.now());
In my modules/custom/MY_MODULE/src/TwigExtension.php
I define the extension here:
public function getFunctions() {
return [
new \Twig_SimpleFunction('MY_MODULE_widget', [$this, 'MY_MODULEWidget']),
];
}
and then it's function:
public function MY_MODULEWidget($MY_VARIABLE)
{
return array(
'#theme' => 'twig_extension_MY_MODULE_widget',
'#MY_VARIABLE' => $MY_VARIABLE,
);
}
The #theme
above is correctly loading my file here modules/custom/MY_MODULE/templates/twig_extension_MY_MODULE_widget.html.twig
:
<div class="MY_CLASS" data-MY_VARIABLE="{{ MY_VARIABLE | url_encode }}">Loading Widget...</div>
Attempt 0:
Added the following twig function to modules/custom/MY_MODULE/templates/twig_extension_MY_MODULE_widget.html.twig
:
{{ attach_library('MY_MODULE/my-twig-extension') }}
but that did not work.
Attempt 1:
Tried adding the library in the render array:
public function MY_MODULEWidget($MY_VARIABLE)
{
return array(
'#theme' => 'twig_extension_MY_MODULE_widget',
'#MY_VARIABLE' => $MY_VARIABLE,
'#attached' => array(
'library' => array(
'MY_MODULE/my-twig-extension',
),
),
);
}
but it doesn't look like BlockBase
logic is supported here to load the library.
Attempt 2:
I looked at how the Twig function attach_library
works and saw how in Drupal\Core\Template\TwigExtension::attachLibrary($library)
worked and tried to implement it here like this:
public function MY_MODULEWidget($job_name)
{
static $doOnce = true;
if ($doOnce) {
$doOnce = false;
/* @var $renderer Drupal\Core\Render\Renderer */
$renderer = \Drupal::service('renderer');
$template_attached = ['#attached' => ['library' => ['MY_MODULE/my-twig-extension']]];
$renderer->render($template_attached);
}
return array(
'#theme' => 'twig_extension_adicio_rated_job_widget',
'#job_name' => $job_name,
);
}
... with the idea of including the library the first time the Twig Extension was called. But no go.
IMPORTANT: yeah I know I can add the following to my module/custom/MY_MODULE/MY_MODULE.info.yml
:
libraries:
- MY_MODULE/my-twig-extension
but I do not want to load this library (very expensive logic), to every page.
Any assistance would be greatly appreciated. Thank you.
twig-extension
Tag to this question.