codeigniter3整合smarty

Codeigniter 3.0+Smarty-3.1.14

1、下载Smarty类库,并放到CI/Controller/libraries;

2、创建控制器,并加载Smarty类,创建Smarty对象,同时设置Smarty关键目录

 

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
    public function index()
    {
        $this->load->library('Smarty');
        $sm=new Smarty();
        $sm->assign('name','明川rtrtrtrtrt');

        $sm->template_dir=base_url().'template/views';
        $sm->compile_dir=FCPATH.'template/html';    //不能用base_url(),会报错
        $pth=FCPATH.'template/views/demo.tpl';

        $sm->display($pth);
        // $this->load->view('welcome_message');
    }
}

 

3、在template/viws文件夹下创建模板文件demo.tpl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    ---------------
    {$name}
</body>
</html>

4、打开控制器方法即可http://www.ci3.com/welcome/index

 

5、使用

将smarty配置保存到文件中(smarty.php)里,放到application/config里面

<?php
$_sm = new Smarty();

$_sm->template_dir = FCPATH . "view/templates";
$_sm->compile_dir = FCPATH . "view/templates_c";

 

 每次调用时引入文件即可

require APPPATH . 'config/smarty.php';
$_sm->assign('name', '李四');
$_sm->display('demo1.tpl');

 

自定义函数:

1、创建helper函数,Myfun_helper.php

创建方法函数:

function fn_info()
  {
    return 1111;
  }

 

2、控制器中,注册方法函数(smarty3.0开始使用registerPlugin)

class Hehe extends CI_Controller
{

  public function __construct()
  {
    parent::__construct();
  }

  public function index()
  {
    require APPPATH . 'config/smarty.php';
    $_sm->registerPlugin('function', 'k_info', 'fn_info');  //注册方法函数
    $_sm->display('demo1.tpl');
  }
}

 

3、视图中调用即可

<body>
    {k_info}
</body>

 

注册块函数

function fn_kuai($arr, $content, $template, $repeat)  //开始标签处$repeat为true,结束标签时$repeat为false
  {
    if ($repeat) {    //默认块函数会调用两遍,第一遍是开始标签,第二遍是结束标签
      return "你的年龄是:{$arr['age']},身高是:{$arr['height']},体重是:{$arr['tizhong']}";
    }
  }

视图中调用

<body>
    {k_info age=38 height=178 tizhong=62 }{/k_info}
</body>

 

posted @ 2023-12-07 11:45  哆啦啊梦  阅读(2)  评论(0编辑  收藏  举报