picocms / Pico

Pico is a stupidly simple, blazing fast, flat file CMS.
http://picocms.org/
MIT License
3.81k stars 616 forks source link

[draft ] Autoload extra stuff #695

Closed digitalinferno closed 2 months ago

digitalinferno commented 3 months ago

If we need to deal with scripts or similar stuff, it's a good practice to manually add them into the twig file, so we can avoid string replacements. But what if we're lazy?

This plugin adds a directory with its template:

    public function  onPageRendering(&$twig, &$twigVariables)
    {
        global $global_array;
        $global_array[] = 'mytpl1.twig';
        $twigVariables['GlobalArray']  = $global_array;
    }    

    public function onTwigRegistered(Twig_Environment &$twig)
    {

        $twig->getLoader()->addPath(__DIR__ . '/theme');
    }

twig:

    <link href=.... >

The theme searches for all .twig files in the array and loads their content:

<head>
...
...
{% for key, var in GlobalArray %}
    {% include GlobalArray[key] %}
{% endfor %}
</head>

It's not stupid if it works. And it works. Can be a good approach?

PhrozenByte commented 3 months ago

Using the Twig Loader to add paths to provide default templates for a plugin's Twig templates is a good common practice, yes.

Not sure about why you're trying to solve with that GlobalArray though. You mean like an API to load a plugin's scripts and stylesheets dynamically? Yes, this is a good idea; it just requires a simple plugin to provide the necessary API and the custom theme to include the necessary HTML to actually include the scripts and stylesheets.

digitalinferno commented 3 months ago

Exactly. You can have multiple plugins (Bootstrap 5, AdSense, code prettifier, etc.). Each plugin adds its path to the appropriate Twig file, and the theme loads them with a loop:

plugins/PicoBoostrap5/theme/boostrap5.twig
plugins/PicoAdsense/theme/adsense.twig
plugins/Picoxxx/theme/xxx.twig

Or a single plugin "loader" who add a single path where the user can put the necessary staff.

plugins/PicoLoader/theme/put here your .twig

Adding a script to a template is not a difficult task, but some fancy/lazy plugins can be useful for enlarging the user base.

PhrozenByte commented 3 months ago

I was rather thinking about a simple PHP API like $themeManager->registerJavascript("plugins/PicoBootstrap5/theme/js/main.js") and $themeManager->registerStylesheet(), basically similar to Grav's asset manager. A single Twig template wouldn't allow one to register both JavaScript files and stylesheets.

digitalinferno commented 3 months ago

So, we just need to add {{ ScriptManager }} inside the <head> tags, and every plugin will load its stuff.

I will return with some strange php. :smile:

github-actions[bot] commented 2 months ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in two days if no further activity occurs. Thank you for your contributions! :+1: