search
HomeBackend DevelopmentPHP TutorialThinkPHP框架视图详细介绍 View 视图-模板(9)

ThinkPHP框架视图详细介绍 View 视图--模板(九)

视图也是ThinkPHP使用的核心部分:


一、模板的使用

a、规则
模板文件夹下[TPL]/[分组文件夹/][模板主题文件夹/]和模块名同名的文件夹[Index]/和方法名同名的文件[index].html(.tpl)

 -->更换模板文件的后缀名(修改配置文件)

'TMPL_TEMPLATE_SUFFIX'=>'.tpl',//更改模板文件后缀名,默认是html


b、修改模板文件目录层次
Tpl/Index/index.html   ==>   Tpl/Index_index.html (改成这种文件目录形式)
      配置文件:
'TMPL_FILE_DEPR'=>'_',//修改模板文件目录层次

c、模板主题(就是网站的不同模板类似QQ装扮皮肤)
-->TP默认是没有主题的,现在模拟建立2个主题模板 my 和 your 文件夹
  Home/Tpl/my/Index/index.html
  Home/Tpl/your/Index/index.html
  想用哪个模板主题,在配置文件中换上对应值即可  
'DEFAULT_THEME'=>'your',  //设置默认模板主题,访问的时候就是your模板下的index
需要在TPL下面新建一个your文件夹作为模板主题文件夹

*如何动态修改模板主题?
1、在后台准备一个功能,修改config.php文件中的默认模板项
2、通过url传递 t=主题 参数可以修改不同的模板
'DEFAULT_THEME'=>'your',//设置默认模板主题
'TMPL_DETECT_THEME'=>true,//自动侦测模板主题
'THEME_LIST'=>'your,my',//支持的模板主题列表要先建立好 my 和 your模板
设置好后这么访问,后面直接带个t参数  t/你的模板文件:
 http://localhost/thinkphp/index.php/Index/index.html/t/my 
 http://localhost/thinkphp/index.php/Index/index.html/t/your


二、输出模板内容
a、display
1.display中没有参数
$this->display();
2.可以带参数
$this->display(本模块文件夹下的其他模板文件);
$this->display('index2');


$this->display(其他文件夹下的模板文件);
$this->display('User:index');  //本模块调用User模块的index文件
//注意,仅仅需要在Tpl下有Public文件夹以及其中的error.html即可
//不需要一定有Public模块--PublicAction.class.php
$this->display('Public:error');


$this->display(其他主题下的 文件夹下的 模板文件);
//需要开启主题支持,DEFAULT_THEME'=>'my'
$this->display('my:Index:index');


$this->display(一个url路径);
$this->display('./Public/error.html');   //public位置在网站根目录下 /public/error.html
//几乎不使用
$this->display('./Public/error.html','utf-8','text/xml');  //模板   编码  显示方式(html或xml)


$content ='这是show的使用直接传html代码';//可能是数据库啊直接拿到的输出来
$this->show($content);    ==  $this->show('这是show的使用直接传html代码');  

3.fetch方法
获得模板文件中的内容,以字符串形式返回
$content=$this->fetch('Public:error');
4.show方法
不需要模板文件,可以直接输出模板内容
$content=$this->fetch('Public:error');
dump($content);
$content=str_replace('h1','i',$content);
$this->show($content);

三、模板中的赋值 : 
//$this->assign('name','乐杨俊');  或
$this->name='乐杨俊2';
$this->display();
模板变量输出:
一、变量输出
1.标量输出  --整型 浮点型 字符型、、、
2.数组输出
$arr = array('k1'=>'leyangjun','k2'=>'leyangjun2');
$this->assign('name',$arr);
$this->display();
模板输出用:
{$name[1]}    --索引数组
{$name['k2']} --关联数组  或
{$name.k1}
3.对象输出
{$name:k}
{$name->k}
二、系统变量(手册详细介绍)
//http://localhost/thinkphp/index.php/Index/add/name/leyangjun 
{$Think.get.name}   --url传的name值,在模板中可以直接拿到输出
{$Think.get.id}
三、使用函数(模板中对变量直接使用PHP函数)
{$name|strtoupper} 生成的编译后文件是 在生成临时文件可见
{$name|date='Y m d H:i:s',###}
四、默认值
{$name|default='这里是默认值'}
五、运算符
+ - * / % ++ --
$this->assign('name',10);
{$name++}   --11
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

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

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

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

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

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.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

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

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version