Why Widgets and not HTML?

2019-08-01 09:18发布

问题:

I've noticed in my development with the Yii framework that there's
a function for many basic HTML elements (CHtml has button, link, etc.) as well as for a menu (that could easily be replaced with a list). My question is it considered ideal to use widgets wherever I can ? When should I use HTML ?

回答1:

Sometimes, frameworks replace basic HTML with their own widgets.

In the case of a link widget, the framework might do additional stuff like automatically giving it class="active" if the link is to the current page, so it can be styled differently.



回答2:

One of the biggest advantages of using widgets is that you automate the HTML code generation, and this means more code/functionality with less coding.

For example, in Yii you have the WidgetFactory (in the config/main) where you can specify the default attributes for all your widgets. Changing the factory defaults changes your whole app/site widgets.

This way, you only deal with some specific view where you may need to adapt your widget behavior.

You may also hack the Widget code to adapt the HTML/js code generation to fit your needs.



回答3:

Widgets are neat wrappers to their HTML equivalents. Widgets in Yii typically also load the required JavaScript libraries. For example the CMaskedTextField in Yii contains a jQuery masked input plugin which it will load together with the widget. Coding the same HTML/JavaScript equivalent will require more lines of code.



标签: yii