


Analysis of the functions and usage of widgets in thinkPHP5 framework
This article mainly introduces the functions and usage of widgets in the thinkPHP5 framework, and analyzes related concepts, usage methods and operating precautions of widgets in thinkPHP5 in the form of examples. Friends in need can refer to the examples in this article
Describes the functions and usage of widgets in the thinkPHP5 framework. Share it with everyone for your reference, the details are as follows:
Note: Use the assistant function return view()
to render, the widget function will fail , must use return $this->fetch()
When we use templates, the top of the general website (such as the navigation bar, or user login area, etc.), and The footer at the end of the website (such as friendly links or copyright notices, etc.) and the body area, in order to simplify the code, we will separate these three parts, and then use them through template inheritance.
But if the top and tail are just pure html code, it's okay, but there are usually logic such as variable assignment, loop traversal, and judgment.
Of course, the original method is that we use native php code in these two areas To implement, but this is not in line with the concept of thinkphp5 framework, so there is widget in the early version. Those who are familiar with WordPress and Yii framework are very familiar with it. These are all built into pendants and widgets.
It is very convenient for you to set output including variable loops in a certain area of the website, such as advertising module, calendar module, etc.
The following will introduce how to set up output in thinkphp5 Simply use this function.
First we need to create a Blog controller in the module directory and resume widget directory, and then write the following code in the index method ; This depends on your habits of using the framework. Of course, if you do not inherit, you need to use the view assistant to render the template.
The meaning of the code is to take out the data in the model Book and assign it to the template.
Key point: $this->fetch(); Don’t think that if you don’t write the template path in it, it will default to only the index view in the blog folder under the view view, This is not possible in widgets, you must fill in the corresponding view pathThe corresponding view path is index.html in the blog directory under the view view, of course you can customize the view name
namespace app\index\widget; use app\index\model\Book; use think\Controller; class Blog extends Controller { public function index() { $list = Book::all(); $this->assign('list',$list); return $this->fetch('widget/index'); } }
Then the code in
view/blog/index.htmlis as follows, for example only
Here the customized output traverses the specified content{volist name="list" id="v"} <p>{$v.id}+{$v.bookname}</p> {/volist}
You can use any functions you want in actual applications, such as navigation bar traversal Output, or how to call many many widget modules
, you can use the following in your specified view template or in an inherited public template
{:widget('Blog /index')}This way to output, Blog is the controller in the widget directory, index is the method name in the controller
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p>这里显示的默认主页输出内容</p> <p>如果widget使用正常,下面将输出遍历一个数据表的内容</p> {:widget('Blog/index')} </body> </html>
At this point, the output of the following page is completed!
Functional analysis of the U method encrypted parameters passed in thinkPHP2 yanyan
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website! Related recommendations:
About the thinkPHP5.0 framework How to configure environment variables
How to use order() in ThinkPHP
The above is the detailed content of Analysis of the functions and usage of widgets in thinkPHP5 framework. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
