grav-plugin-shortcode-core icon indicating copy to clipboard operation
grav-plugin-shortcode-core copied to clipboard

Assets not loaded when using shortcode only in Twig

Open nbusseneau opened this issue 3 years ago • 11 comments

Hello,

There is an issue where shortcodes used only in Twig templates (and not content) will not load assets correctly if they are added as recommended from examples (from the process function passed when adding a new shortcode handler).

Minimal plugin reproducing the issue: shortcode-asset-twig-demo.zip

Steps:

  • Install plugin. Note that blank.js is supposed to be loaded L19 in AssetTwigDemoShortcode.php while processing assetTwigDemo shortcode.
  • Create a page with shortcode [assetTwigDemo] in content.
  • Asset is loaded: <script src="/user/plugins/shortcode-asset-twig-demo/blank.js"></script> will be added to generated page.
  • Delete shortcode from content.
  • In page template, try to process the same shortcode: {{ '[assetTwigDemo]'|shortcodes }}
  • Asset is NOT loaded: <script src="/user/plugins/shortcode-asset-twig-demo/blank.js"></script> missing in generate page.

This is because Twig shortcodes are processed directly via https://github.com/getgrav/grav-plugin-shortcode-core/blob/793bcd3f4c04ae41e35544adba01a92527513561/classes/plugin/ShortcodeManager.php#L283-L289 rather than https://github.com/getgrav/grav-plugin-shortcode-core/blob/793bcd3f4c04ae41e35544adba01a92527513561/shortcode-core.php#L110-L146 which is the code responsible for preparing assets insertion into page, along with its sibling https://github.com/getgrav/grav-plugin-shortcode-core/blob/793bcd3f4c04ae41e35544adba01a92527513561/shortcode-core.php#L173-L204

Two simple workarounds:

  • Add a commented shortcode to content, like <!-- [assetTwigDemo] -->. The shortcode will be correctly processed (thus, assets are loaded), but since it's commented it won't render anything on the page. This has the disadvantage of leaving a comment in the generated source code.
  • Add assets directly on shortcode init() rather than in the process function. You can uncomment L19 in AssetTwigDemoShortcode.php to test this workaround. This has the disadvantage of loading assets for this shortcode on all pages, even when no shortcode of this type is present.

I guess the proper solution would be to load assets not only when processing content but also when processing Twig directly. What do you think? If you like this approach, I'm willing to try my hand at an implementation.

Cheers!

nbusseneau avatar Aug 26 '20 23:08 nbusseneau