thinkphp 自定义标签

发布于 20 天前  18 次阅读


1.创建tag 标签类

<?php

class GuyiTag extends TagLib
{
    /**
     * 自定义标签库,用于处理图片上传和图片显示。
     *
     *
     *
     * 标签参数说明:
     * - **module**: (string) 上传模块的名称,例如 'long'。
     * - **ids**: (string) 附件的 ID 列表,用逗号分隔,例如 '3380,3309'。
     * - **type**: (string) 文件类型,例如 'file' 或 'image'。
     * - **name**: (string) 输入框的 name 属性值。
     * - **idName**: (string) 外层 `<div>` 的 ID 名称,例如 'text_name'。
     * - **url**: (string) 文件上传的地址或 API 接口路径。
     * - **hideUp**: (boolean) 是否隐藏上传按钮,`true` 表示隐藏,`false` 表示显示。
     * - **accept**: (string) 文件格式限制,例如 'mp4,mp3,image/*'。
     * - **limit**: (int) 文件上传的最大数量,例如 9。
     */

//   用法示例
//   {GuyiTag:image name="cad_image"  ids="$info.cad_image" type="file" idName="cad_image"}
//           <div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">
//               <input type="hidden" name="cad_image[]" value="{$vo.id}">
//               <div class="file-upload-icon-class" style="background: url(/static/ico/{$vo.ext}.png);"></div>
//               <span>{$vo.name}</span>
//               <div class="del"></div>
//           </div>
//   {/GuyiTag:image}
//
//   {GuyiTag:imagediv name="cad_image"  ids="$info.cad_image" type="file" idName="cad_image" }

    protected $tags = [
        'image' => ['attr' => 'module,ids,type,name,idName,url,hideUp,accept,limit', 'close' => 1],
        'imagediv' => ['attr' => 'module,ids,type,name,idName,url,hideUp,accept,limit', 'close' => 0],
    ];

    public function tagImage($tag, $content)
    {
        $ids = $tag['ids'];
        $type = $tag['type'];
        $item = $tag['item'] ?? 'vo';
        $name = $tag['name']??'default_name';
        $ID = $tag['idName']??$name;
        $key = $tag['key'] ?? 'key';
        $hideUp = $tag['hideUp'] ?? false;
        $accept = $tag['accept'] ?? '[]';
        $limit = $tag['limit'] ?? 9;
        $module= $tag['module'];
        $url= $tag['url']??'/api/upload/uploadOasFile';
        if (strpos($ids, '$') === 0) {
            $ids=  $this->autoBuildVar($ids);
        }

        if($type=='file'){
            $class = 'wxcui-fileUpload-list';
            $previewImage='preview-image';
            $jsClass = "WxcuiFileUpload";
        }else{
            $class = "wxcui-file-list";
            $previewImage='preview-image';
            $jsClass ="WxcuiUpload";
        }

        if(empty($accept)){
            $accept ='[]';
        }else{
            $accepts = string_to_array($accept,',');
            $acceptText ='[';
            foreach ($accepts as $v){
                $acceptText.="'".$v."'".",";
            }
            $acceptText=rtrim($acceptText,',');
            $acceptText.=']';
            $accept =$acceptText;
        }

        $divStart = '<div id="'.$ID.'" class="'.$class.'" '.$previewImage.'>';
        $returnVarName = $name.'List';
        $divEnd ='</div>';

        if($hideUp){
            $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">
                        <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                        <div class="file-upload-icon-class" style="background: url(/static/ico/{$vo.ext}.png);"></div>
                        <span>{$vo.name}</span>                      
                    </div>';
            $javascript = "";
        }else{
            $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">
                        <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                        <div class="file-upload-icon-class" style="background: url(/static/ico/{$vo.ext}.png);"></div>
                        <span>{$vo.name}</span>
                        <div class="del"></div>
                    </div>';
            $javascript = "<script>
                        var uploadFormImages = new ".$jsClass."({
                            elem: '#".$ID."',
                            name: '".$name."',
                            url: '".$url."',
                             limit: ".$limit.",
                            params: {
                                module: '".$module."',                                
                            },
                            accept: ".$accept."
                        });
                    </script>";
        }

        if(empty($ids)){
            $selectStr ="<?php           
            \${$returnVarName} = [];
            ?>";
        }else{
            $selectStr = "<?php           
            \${$returnVarName} = app\GuyiTag::getFieldList({$ids}??[],'{$type}');
            ?>";
        }

        $parse = <<<parse
            $divStart
            {$selectStr}       
                {volist name="{$returnVarName}" id="{$item}" key="{$key}"}
                {$content}
                {/volist}
             $divEnd          
             {$javascript}
            parse;
        return $parse;
    }

    public function tagImagediv($tag, $content)
    {
        $ids = $tag['ids']??[];
        $type = $tag['type'];
        $name = $tag['name']??'default_name';
        $ID = $tag['idName']??$name;
        $item = $tag['item'] ?? 'vo';
        $key = $tag['key'] ?? 'key';
        $limit = $tag['limit'] ?? 9;
        $accept = $tag['accept']??[];
        $hideUp = $tag['hideUp'] ?? false;
        $module= $tag['module'];
        $url= $tag['url']??'/api/upload/uploadOasFile';
        if (strpos($ids, '$') === 0) {
            $ids=  $this->autoBuildVar($ids);
        }
        if(empty($accept)){
            $accept ='[]';
        }else{
            $accepts = string_to_array($accept,',');
            $acceptText ='[';
            foreach ($accepts as $v){
               $acceptText.="'".$v."'".",";
            }
            $acceptText=rtrim($acceptText,',');
            $acceptText.=']';
            $accept =$acceptText;
        }

        if($type=='file'){
            $class = 'wxcui-fileUpload-list';
            $previewImage='preview-image';
            $jsClass = "WxcuiFileUpload";
        }else{
            $class = "wxcui-file-list";
            $previewImage='preview-image';
            $jsClass ="WxcuiUpload";
        }
        $returnVarName = $name.'List';
        $divStart = '<div id="'.$ID.'" class="'.$class.'" '.$previewImage.'>';

        $divEnd ='</div>';

        if($hideUp){
            if($type=='file'){
                $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">                        
                        <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                        <div class="file-upload-icon-class" style="background: url(/static/ico/{$vo.ext}.png);"></div>
                         <span> <a href="{$vo.url}" TARGET="_blank" download="{$vo.name}" style="text-decoration: none; color: inherit;">{$vo.name}</a></span>    
                       </div>';
            }else{
                $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">                        
                        <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                        <img src="{$vo.thumbnail_path}">
                       </div>';
            }

            $javascript = "";
        }else{
            if($type=='file'){
                $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">
                            <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                            <div class="file-upload-icon-class" style="background: url(/static/ico/{$vo.ext}.png);"></div>
                            <span>{$vo.name}</span>
                            <div class="del"></div>
                           </div>';
            }else{
                $divStr = '<div data-image="{$vo.url}" data-alt="{$vo.name}" class="file-item">
                            <input type="hidden" name="'.$name.'[]" value="{$vo.id}">
                            <img src="{$vo.thumbnail_path}">
                            <div class="del"></div>
                           </div>';
            }

            $javascript = "<script>
                        var uploadFormImages = new ".$jsClass."({
                            elem: '#".$ID."',
                            name: '".$name."',
                            url: '".$url."',
                             limit: ".$limit.",
                            params: {
                                module: '".$module."',
                            },
                            accept: ".$accept.",
                        });
                    </script>";
        }

        if(empty($ids)){
            $selectStr ="<?php           
            \${$returnVarName} = [];
            ?>";
        }else{
            $selectStr = "<?php           
            \${$returnVarName} = app\GuyiTag::getFieldList({$ids}??[],'{$type}');
            ?>";
        }

        $parse = <<<parse
             
            {$selectStr}
              {$divStart}            
                {volist name="{$returnVarName}" id="{$item}" key="{$key}"}
                   {$divStr}
                   {$content}
                {/volist}
              {$divEnd} 
              {$javascript} 
            parse;
        return $parse;
    }

    public static function getFieldList($ids, $type)
    {
        if(empty($ids)) return [];
        $ids = is_array($ids)?array_to_string($ids):$ids;
        try {
            if ($type === 'file') {
                return OasFile::getImageList($ids);
            } else {
                return OasFile::getImageList($ids);
            }
        } catch (Exception $e) {
            error_log("oss获取图片报错: " . $e->getMessage());
            return false;
        }
    }
}

2.再config view 中加入配置

'taglib_pre_load'     =>    'app\XnmsTag',
ℳ๓古依博學之誌°ꦿ⁵²º᭄
最后更新于 2025-01-02