-
Notifications
You must be signed in to change notification settings - Fork 18
Description
I'm trying out shortcodes-core
v5.2.0 and it appears that default shortcode classes load assets from the handler function, i.e. each time it is called to process the shortcode on a page. E.g. in FontAwesomeShortcode
there is:
$this->shortcode->getHandlers()->add('fa', function(ShortcodeInterface $sc) { | |
// Load assets if required | |
if ($this->config->get('plugins.shortcode-core.fontawesome.load', false)) { | |
$this->shortcode->addAssets('css', $this->config->get('plugins.shortcode-core.fontawesome.url')); | |
} |
This is ineffective and also may lead to problems with processing shortcodes in certain situations. One such situation is the default error page of the Quark theme. If I add a shortcode to the default footer.html.twig
template using this form:
{{ '[fa=grav extras=fab/]'|shortcodes|raw }}
then the icon won't display because fontawesome.css
(whatever is configured in plugins.shortcode-core.fontawesome.url
) is not loaded on the page Grav generates as a result of accessing an invalid URL on the web site (basically, a default grav-admin-v1.7.46
installation). Please note that in order to reproduce the problem you need to remove loading Grav-supplied FontAwesome from stylesheets
block of the default Quark's base.html.twig
template (or the icon will come from there, of course).
It's worth mentioning that the shortcode itself is handled fine in this place using the shortcode
Twig filter. I.e. I get
<i class="fab fa-grav"></i>
in the resulting page's HTML. It's only that fontawesome.css
is not there, so the browser doesn't know where to get fab
and fa-grav
styles from and displays nothing.
If I move the addAssets
call out of the handler function to the init
function like this:
public function init()
{
// Load assets if required
if ($this->config->get('plugins.shortcode-core.fontawesome.load', false)) {
$this->shortcode->addAssets('css', $this->config->get('plugins.shortcode-core.fontawesome.url'));
}
$this->shortcode->getHandlers()->add('fa', function(ShortcodeInterface $sc) {
then all starts to work smoothly — the CSS is there and the icon "magically" appears.
I'm not a PHP/Twig/Grav expert but I guess the reason is that by the time when the handler function is executed while generating the error page, its assets are already processed by Grav so addAssets
has no effect. It's not the case with the init
call because it seems to be called somewhere at the very beginning, so the CSS asset is correctly added to every involved page.
And as I mentioned before, it really makes no sense to call addAssets
each time the shortcode gets processed. It's a meaningless waste of resources.
Grepping in /user/plugins/shortcode-core/classes/shortcodes
for addAssets
shows that SafeEmailShortcode.php
and NoticeShortcode.php
suffer from exactly the same problem. Asset loading should be done once and init
itself is a perfect place for that IMO.