1

I am developing a plugin for Craft 3. And I am trying to add some content to all pages in the CMS using this plugin. How can I do that? Is there a method or class call I can use for this? I am not sure where this is mentioned in the docs either.

Basically I want to add a few lines of HTML, CSS and JS in all the pages of the CMS if my plugin is installed and enabled in that Craft installation. Any ideas, anyone?

  • Could you explain your use case for this? There could be a more suitable solution for this. – Johannes Jun 8 at 18:22
1

With your plugin you can check for a front-end request, and if so inject an asset bundle


public function init()
{
    // Check if front end request

    $request = Craft::$app->getRequest();
    if (
        $this->isInstalled
        && !$request->isCpRequest
        && !$request->isConsoleRequest
     ) {
        $this->registerAssetBundles();
    }
}

protected function registerAssetBundles()
{
    // Include CSS on front end
    $view = Craft::$app->getView();
    $view->registerAssetBundle('vendor\\plugin-handle\\assetbundles\\YourpluginFrontendAssets');
}

I'm not sure it's possible to inject html, I believe you would need to write a new variable to render your html.

| improve this answer | |
  • This worked like a charm. Thank you kind sir. :) Small question, if I had to add attributes to my js and css files, how to do that in the asset bundle? – Rohan Jun 12 at 13:16
  • $jsOptions Figured it out :) – Rohan Jun 12 at 13:25
1

If you are able to place a hook tag in all templates then you could register a new template hook method in your plugin.

Twig:

{% hook 'my-custom-hook-name' %}

Your plugin:

Craft::$app->view->hook('my-custom-hook-name', function(array &$context) {
    $context['foo'] = 'bar';
    return '<p>Hey!</p>';
});

For injecting CSS or JS you would use

\Craft::$app->getView()->registerCssFile("file.css");
\Craft::$app->getView()->registerJsFile("file.js");

If you can't modify the template files to place a hook tag there you could dynamically generate the markup in your JS file, depending on your use case.

| improve this answer | |
1

You should be able to listen for the before render event on the view class.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.