getgrav / getgrav/grav-plugin-shortcode-core
Assets not loaded when using shortcode only in Twig
- Dominant language
- PHP
- Stars
- 47
- Forks
- 17
- PR merge metrics
- No merged PRs in 30d
Description
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](https://github.com/getgrav/grav-plugin-shortcode-core/files/5133114/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: `` 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: `` 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 ``. 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!
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.