Reputation: 753
I'm looking for a way to add a widget to the final view without modifiying View or layout file.
imagine you are creating a composer package which contains a Bootstrap class(a class which implements yii\base\BootstrapInterface ) and a simple widget which is responsible to display a simple timer .
you want to add this widget to all Views in all web responses..how you do this?
I don't like to touch my view files or layout files , I'm just tryng to create a package which must do this by itself.
Upvotes: 0
Views: 640
Reputation: 2497
Assuming you are using yii2 here, and you must not touch the layout and view files.
You can
1. Use the afterRender Function
For this you will need to override the View class, add your own afterRender
function that processes the page and adds your widget(s) as per your own defined rules.
Then you can call
$this->view->on('afterRender', ...);
to do whatever you want on after render.
Since the controller calls the default view class, you will also need to override the yii\web\controller class and change the view class used.
2. Use Javascript to get widget and display to user
Add a javascript that will append the widget element at the correct place, fetched using ajax from a separate independent (partial) view file .
3.In case if developing an extension
You can trigger a function on the view body begin or end in your bootstrap function
$app->on(Application::EVENT_BEFORE_REQUEST, function () use ($app) {
$app->getView()->on(View::EVENT_END_PAGE, [$this, 'renderWidget']);
});
And add a renderWidget function similar to this :
public function renderWidget($event){
$view = $event->sender;
echo "extra html at end of page";
}
Upvotes: 2