seunex17 / codeigniter4-smarty

v1.3.0 2024-05-08 18:42 UTC

This package is auto-updated.

Last update: 2024-09-08 20:43:22 UTC


README

GitHub Hits Packagist Downloads Packagist PHP Version Support GitHub stars

轻松将Smarty模板引擎实现到您的CodeIgniter 4项目中。

描述

使用这个干净且语义化的预构建Smarty模板,在CodeIgniter 4中将应用程序逻辑与表示层分离。

要求

  • Codeigniter 4.x
  • Smarty 5.x

安装

最佳安装方式是通过Composer,您可以使用以下命令:

composer require seunex17/codeigniter4-smarty

这将简单地将最新的ci4-smarty版本添加到您的项目中作为模块。

示例

默认情况下,无需任何额外配置,此库将自动在Views/templates/default目录中查找您的模板文件。

以下是一个基本使用示例

  • PHP
<?php 
namespace App\Controllers;

use Seunex17\Codeigniter4Smarty\Template\Smartie;

class Home extends BaseController
{
   public function index() {
		
      return Smartie::view('test');
  }
}

如果您的视图文件位于子目录中,例如Views/dashboard/test.tpl,您可以通过以下示例加载视图文件:

  • PHP
<?php 
namespace App\Controllers;

use Seunex17\Codeigniter4Smarty\Template\Smartie;

class Home extends BaseController
{
   public function index() {
		
      return Smartie::view('dashboard.test');
  }
}

从控制器传递数据到视图

  • PHP
<?php 
namespace App\Controllers;

use Seunex17\Codeigniter4Smarty\Template\Smartie;

class Home extends BaseController
{
   public function index() {
	
      return Smartie::view('test', [
         'message' => 'smarty template engine',
         'title' => 'Showing example on how to use smarty'
      ]);
   }
}
  • 视图

app/Views/test.tpl

<!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>{$title}</title>
   </head>
   <body>
	This is a message from controller: {$message}
   </body>
</html>

在视图中使用原生和自定义PHP函数

在smarty v5版本中,已删除原生和自定义PHP函数的使用。如果我们需要在视图中使用函数,我们需要注册这些函数并告诉smarty我们打算使用这些函数。

  • 将Smartie核心配置发布到您的应用
php spark smartie:publish

您发布的文件现在应位于app/Configs/Smartie.php

  • 注册您的函数
public array $modifiers = ['base_url', 'site_url'];
  • 声明全局变量
public array $globalVariables = ['name', 'John Doe'];

要了解更多关于smarty标签的信息,您可以在此处查看smarty官方文档:https://smarty-docs.php.ac.cn/smarty/stable/


贡献

所有贡献都极受赞赏。