search
HomePHP FrameworkThinkPHPAnalyzing the use of ThinkPHP5.1 custom tags

The following tutorial column will introduce you to the use of parsing ThinkPHP5.1 custom tags. I hope it will be helpful to friends in need!

Recently, there are projects that need to use custom tags. TP uses 5.1. Please note that 5.1 has major changes in the directory structure and procedures compared to 5.0. . Pay attention to your version. Let’s get to the point.

Analyzing the use of ThinkPHP5.1 custom tags1. Create the tag function file

Create the directory tabLib in the model directory, and create a Cms.php in the directory

namespace app\cms\tagLib;
use think\Db;
use think\template\TagLib;

class Cms extends TagLib{

    protected $tags = [
        //标签定义: attr 属性列表,close 是否闭合(0或1,默认1),alias标签别名 level嵌套层次
        'lists' => ['attr' => 'num,order,sort'],
    ];

    // 当不使用content的时候,闭合标签没有效果
    // 修改过此文件后,需要改动下模板的内容,否则模板有缓存不会执行新的内容。
    public function tagLists($tag,$content){
        $cateID = $tag['cate_id']; //栏目ID
        $num    = $tag['num']; //数量
        $order  = input($tag['order']); //排序方式
        $type = $cateID;
        $name = $tag['name'];
        $tableName = 'table_name';
        $parse = &#39;<?php $map=[];&#39;;
        $parse .= &#39;$__LIST__ = Db::name(&#39;.$tableName.&#39;)->where(["cate_id"=>&#39;. $cateID .&#39;])
            ->limit(&#39;.$num.&#39;)
            ->select(); ?>&#39;;
        $parse .= &#39;{volist name="__LIST__" id="&#39;. $name .&#39;"}&#39;;
        $parse .= $content;
        $parse .= "{/volist}";
        return $parse;
    }

Encountered doubts during development:

1. The above tagLists function corresponds to the tag definition in protected $tags. Pay attention to the capitalization, otherwise the function will not be found.

2. All characters in $parse are assembled strings. This string will be parsed again by TP's template tag, so you can use TP's original tags or native PHP statements in it. However, you cannot pass an external Array or object into $param as a parameter. You must know that it is just a string used for assembly. Please note the use of the $__LIST__ variable. If you want to read data from the database, you must write a complete PHP code. You cannot execute the query outside and then pass in the queried list as a variable.

2. Load this tag function in the template configuration information

Add a sentence in the module cms/config/template.php:

'taglib_pre_load' => 'app\cms\ tagLib\Cms',

If you do not have this file, you can copy a template in the config directory in the root directory and put it in the cms/config directory. 3. Use tags in templates.

  {cms:lists name="row" num="10" cate_id="5" order="1"}
        <li>{$row.title}</li>
    {/cms:lists}

Name, num, cate_id and other attributes will be passed in as the first parameter $tags of tagLists. The content between {cms:lists} and {$/cms:lists} will be passed into the second parameter of tagLists as a complete string $content.

Note: There are closed tags and non-closed tags here. If it is a closed tag, you must use content in (1). If it is a non-closed tag, you do not need to use it. If you do not use the content variable, the closed tag {/cms:lists} will be output as is and will not be parsed.

There is so much confusion for the time being, and the issue of paging lists is still being studied. I will add it after the study is completed.

Supplement: Do not perform data type conversion on the data obtained in the $tag[] array in tagList, because when a variable is passed, this variable will not take effect! ! So it is wrong to use intval($tag[num]) here.

The above is the detailed content of Analyzing the use of ThinkPHP5.1 custom tags. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
What is the difference between think book and thinkpadWhat is the difference between think book and thinkpadMar 06, 2025 pm 02:16 PM

This article compares Lenovo's ThinkBook and ThinkPad laptop lines. ThinkPads prioritize durability and performance for professionals, while ThinkBooks offer a stylish, affordable option for everyday use. The key differences lie in build quality, p

How can I use ThinkPHP to build command-line applications?How can I use ThinkPHP to build command-line applications?Mar 12, 2025 pm 05:48 PM

This article demonstrates building command-line applications (CLIs) using ThinkPHP's CLI capabilities. It emphasizes best practices like modular design, dependency injection, and robust error handling, while highlighting common pitfalls such as insu

How to prevent SQL injection tutorialHow to prevent SQL injection tutorialMar 06, 2025 pm 02:10 PM

This article explains how to prevent SQL injection in ThinkPHP applications. It emphasizes using parameterized queries via ThinkPHP's query builder, avoiding direct SQL concatenation, and implementing robust input validation & sanitization. Ad

How to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityHow to deal with thinkphp vulnerability? How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:08 PM

This article addresses ThinkPHP vulnerabilities, emphasizing patching, prevention, and monitoring. It details handling specific vulnerabilities via updates, security patches, and code remediation. Proactive measures like secure configuration, input

How to install the software developed by thinkphp How to install the tutorialHow to install the software developed by thinkphp How to install the tutorialMar 06, 2025 pm 02:09 PM

This article details ThinkPHP software installation, covering steps like downloading, extraction, database configuration, and permission verification. It addresses system requirements (PHP version, web server, database, extensions), common installat

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityHow to fix thinkphp vulnerability How to deal with thinkphp vulnerabilityMar 06, 2025 pm 02:04 PM

This tutorial addresses common ThinkPHP vulnerabilities. It emphasizes regular updates, security scanners (RIPS, SonarQube, Snyk), manual code review, and penetration testing for identification and remediation. Preventative measures include secure

How to use thinkphp tutorialHow to use thinkphp tutorialMar 06, 2025 pm 02:11 PM

This article introduces ThinkPHP, a free, open-source PHP framework. It details ThinkPHP's MVC architecture, features (routing, database interaction), advantages (rapid development, ease of use), and disadvantages (potential over-engineering, commun

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.