maheswara / ci4smarty

集成CodeIgniter 4和Smarty模板引擎

v1.0.0 2022-04-16 09:46 UTC

This package is auto-updated.

Last update: 2024-09-16 15:23:25 UTC


README

集成CodeIgniter 4和Smarty模板引擎

需求

  • PHP 7.3+, 8.0+
  • CodeIgniter 4.0.4+
  • Smarty 4.1.0+

安装

最好通过Composer安装。假设Composer已全局安装,您可以使用以下命令

> composer require maheswara/ci4smarty

手动安装

否则,您可以手动安装

  1. 下载 smartyci4smarty,并将其放入 app/ThirdParty 文件夹

  2. 编辑并添加以下行到 app/Config/Autoload.php

     public $psr4 = [
         'Ci4Smarty'   => APPPATH . 'ThirdParty/ci4smarty-1.0.0/src'
     ];
    
     public $classmap = [
         'Smarty'   => APPPATH . 'ThirdParty/smarty-4.1.0/libs/Smarty.class.php',
     ];
    

控制器

实现此功能的一种简单方法是扩展控制器自 SmartyController

use Ci4Smarty\Controllers\SmartyController;

class BaseController extends SmartyController{
    
}

配置

您可以通过将文件 SmartyConfig.php 添加到 app/Config 文件夹并对其进行修改来覆盖配置

<?php
    namespace Config;
    use CodeIgniter\Config\BaseConfig;
    class SmartyConfig extends BaseConfig
    {
        public static $fileExtension = '.tpl';
        public static $templateDir = APPPATH . 'Views';
        public static $compileDir = WRITEPATH . 'templates_c';
        public static $cacheDir = WRITEPATH . 'caches';
        public static $configDir = APPPATH . 'Views/configs';
    }

功能

这是功能列表

  • 自动根据控制器类和方法渲染模板,如: home/index 或如果URL段位于文件夹下,如: admin/dashboard/index
  • 您也可以手动渲染: $this->render('home/index');$this->render('home/index', $data); 其中 $data 是数组或对象
  • 如果您想更改布局,可以在渲染之前添加 $this->setLayout('layout');,并在布局文件中添加 {$content} 作为已渲染模板的容器
  • 您还可以使用smarty的 {extend} 语法来实现布局
  • 如果您想停止渲染以进行调试或打印_r您的代码并消除默认异常,可以使用 $this->setRendered(true);
  • 不要忘记每个模板文件的扩展名是 .tpl(smarty)