When we use the same dynamic block of code on multiple view pages, it is necessary to have a thinkphp widget extension.
The widget is equivalent to invoking a controller of a dedicated widget on the page and inserting its associated view into the current page, so the widget's view content is considered in the context of the current page.
Let me give you an example.
Requirements: Write a Theme widget for the page, and multiple pages to extract all the topics from the database and list them in the page, to achieve a theme filtering function.
Application page:
<!--theme- -<dt class= "Filter_cat" > Theme:</dt> {: W (' Common/subject/index ')} </dl >
This is how widgets are applied, with parameters in the form of
{: W (' Common/subject/index ', array (' id ' = = $id)}
So he's equivalent to accessing the index method in the subject controller, but his definition is different from the controller.
Define a controller for the widget, define a file in the Widget folder under the same path as the Controller folder
SubjectWidget.class.php
<span style= "FONT-SIZE:18PX;" ><?phpnamespace common\widget;use Think\controller;class Subjectwidget extends Controller {public function Index ($language _id=1) { //theme $subject _lists = Get_result (D (' Common/categoryview '), array (' status ' =>1, ' Type ' = ' subject ', ' language_id ' = $language _id)); $this->assign (' subject_lists ', $subject _lists); $this->display (T (' [email protected]/subject/index ') }} </span>
Index.html
<?php $options _arr=array_merge (I (' Get. '), array (' subject ' = ') '); $href =u (', $options _arr); ?> <dd class= "Filter_con" > <ul> <li class= "item "><a <?php if (! I (' Get.subject ')) {>class= "cur" <?php}?> href= "<?= $href?>" > All </a></li> <?php $options _arr=i (' Get. '); unset ($options _arr[' subject '); foreach ($subject _lists as $val) {$options _arr=array_merge (' Get. '), array (' subject ' = $val [' description_id ']); $href =u (', $options _arr); ?> <li class= "item" ><a <?php if (I (' get.subject ') = = $val [' description_id ']) {? >cla ss= "cur" <?php}?> href= "<?= $href?>" ><?= $val [' title ']?></a≫</li> <?php}?> </dd>
As shown above, this is what is actually displayed on the main page, and all of the page's classes are defined or referenced on the main page, if you write a relative URL, such as U (") represents the main interface belongs to the current controller under the current method, is not a widget controller or method, so, From this you can see that the widget is fully service to the calling interface