0

Want to override index.twig content through a custom plugin. I want to create a plugin that appends some content on website homepage. How to Achieve this any reference will be helpful

5

You can inject HTML to the end of the body using View Events:

use craft\web\View;
use yii\base\Event;

Event::on(
    View::class,
    View::EVENT_END_BODY,
    function() { echo 'Foobar'; }
);

The output of this function will appear wherever the endBody() function is placed in the index.twig. The event will even work if the template doesn't contain this function, because Craft will dynamically insert it before the </body> end tag.

If you want to register CSS or JS assets, use the methods registerCssFile and registerJsFile on \Craft::$app->view instead. There's also a registerHtml method that achieves the same as the hook above.


While there are valid use-cases for injecting HTML, it's a terrible idea for most plugins. As a developer, I won't touch your plugin if it forcibly injects any code into my frontend template without letting me have a say in it. Instead, your plugin could expose a custom variable or function to Twig and allow me to call it myself. This way, I have control over if and where your injected content is placed. Just something to keep in mind as an alternative to the hooks above.

5
  • We are trying to override the website index.twig file considering it as home page. We are trying to craete a plugin that will add a layout to home page like some banner with content is it possible with this ?
    – Dss
    Jan 4 at 11:34
  • 2
    @DotSquares Yes, but you won't get a step-by-step guide with code to copy and paste here. Please read the documentation articles I linked and consider the caveat below the line. Then build your plugin as far as you can and if you hit specific problems, post it as a question.
    – MoritzLost
    Jan 4 at 11:40
  • Thanks for the reply but with this method it won't override the homepage code it will inject my code with users' code at the end of the body I want to create a 404 page kind of plugin that will show some text to non logged in users.
    – Dss
    Jan 5 at 10:51
  • @DotSquares So do you want to overwrite the homepage or the 404 page? It sounds like you're going down the wrong rabbit hole. Maybe post post some more information in what you're trying to do with this plugin, I'm sure there is a better solution.
    – MoritzLost
    Jan 5 at 10:57
  • I am trying to create an under construction plugin if the user enables the maintenance mode in the plugin the homepage will show some maintenance template text to non-logged users. just like a 404 template page layout
    – Dss
    Jan 5 at 11:00

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.