CodeIgniter+Smarty配置

最近在学习CodeIgniter框架,但是之前都在搞ECSHOP,对smarty情有独钟,便想着将其整合进来使用,现整理一下整合方法:

1.下载 CodeIgniter 的源码包并且解压,并在项目目录下views\下新建 templates,templates_c 文件夹待用

2.下载 Smarty 源码包中的libs核心类库重命名为Smarty-3.1.13(文件夹名字自定,但在Smarty.php配置时要对应)并且将文件夹copy到ci的项目目录下的third_party下,同时在libraries文件夹下建立Smarty.php文件,并将 附件 中ci项目目录下third_party\Smarty-3.1.13\plugins 的5个文件放入plugins文件夹下

/*Smarty plugin functions to bridge to CodeIgniter classes*/
plugins/function.ci_config.php
plugins/function.ci_db_session.php
plugins/function.ci_form_validation.php
plugins/function.ci_language.php
plugins/function.ci_validation.php

3.在Smarty.php文件写入以下代码

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

/**
 * Smarty Class
 *
 * @package        CodeIgniter
 * @subpackage    Libraries
 * @category    Smarty
 * @author        Kepler Gelotte
 * @link        http://www.coolphptools.com/codeigniter-smarty
 */
/*
|--------------------------------------------------------------------------
| Smarty Directory by cuore 2013-4-2 
|--------------------------------------------------------------------------
*/
define
('SMARTY_DIR', APPPATH . 'third_party/Smarty-3.1.13/'); require_once( SMARTY_DIR .'Smarty.class.php' ); class CI_smarty extends Smarty { function CI_smarty() { parent::Smarty(); $this->compile_dir = APPPATH . "views/templates_c/"; $this->template_dir = APPPATH . "views/templates/"; $this->assign( 'APPPATH', APPPATH ); $this->assign( 'BASEPATH', BASEPATH ); log_message('debug', "Smarty Class Initialized"); } function __construct() { parent::__construct(); $this->compile_dir = APPPATH . "views/templates_c/"; $this->template_dir = APPPATH . "views/templates/"; $this->assign( 'APPPATH', APPPATH ); $this->assign( 'BASEPATH', BASEPATH ); // Assign CodeIgniter object by reference to CI if ( method_exists( $this, 'assignByRef') ) { $ci =& get_instance(); $this->assignByRef("ci", $ci); } log_message('debug', "Smarty Class Initialized"); } /** * Parse a template using the Smarty engine * * This is a convenience method that combines assign() and * display() into one step. * * Values to assign are passed in an associative array of * name => value pairs. * * If the output is to be returned as a string to the caller * instead of being output, pass true as the third parameter. * * @access public * @param string * @param array * @param bool * @return string */ function view($template, $data = array(), $return = FALSE) { foreach ($data as $key => $val) { $this->assign($key, $val); } if ($return == FALSE) { $CI =& get_instance(); if (method_exists( $CI->output, 'set_output' )) { $CI->output->set_output( $this->fetch($template) ); } else { $CI->output->final_output = $this->fetch($template); } return; } else { return $this->fetch($template); } } } // END Smarty Class /* End of file Smarty.php */ /* Location: ./application/libraries/Smarty.php */

PS:这里的smarty相关配置属性(template_dir,compile_dir,left_delimiter,right_delimiter等)可以写到项目目录下的config文件夹下新建的smarty.php文件内,也可以如上直接写入

<?php

    if (! defined('BASEPATH')) exit('no direct base');

    $config['template_dir'] = APPPATH.'views/template/';

    $config['compile_dir']  = APPPATH.'views/template_c/';

?>

如写入config\smarty.php,并在项目目录下的config文件夹中的autoload.php文件的config的最后加入smarty,然后在libraries\Smarty.php如下便可获取配置

$this->ci = &get_instance(); 

//$this->ci->load->config('smarty');//加载smarty的配置文件,如已自动则不需要此行

$this->template_dir = $this->ci->config->item('template_dir'); $this->compile_dir = $this->ci->config->item('compile_dir');

4.在项目目录下的config文件夹中的autoload.php文件libraries的最后加入smarty

/*默认是空的,直接加入便可:$autoload['libraries'] = array('smarty');*/
$autoload['libraries'] = array('旧有配置','smarty');//已有相关配置,在最后加入

便可以自动加载配置了,否则便要在每次在使用smarty时load

    class Example extends CI_Controller
    {
        function __construct()
        {
            parent::__construct();
            //$this->load->library('smarty');
  
        }
    }

5.在项目目录下core文件夹下新建MY_Controller.php (这不是必须的,但是我想 这样在书写$this->smarty->assign();$this->smarty-display();的时候舒服一些,所以附件中的MY_Controller.php不是必须的)

<?php if (!defined('BASEPATH')) exit('No direct access allowed.');
     
    class Controller extends CI_Controller {
     
        public function __construct() {
     
            parent::__construct();
     
        }
     
        public function assign($key,$val) {
            $this->smarty->assign($key,$val);
        }
     
        public function display($html) {
            $this->smarty->display($html);
        }
    }
?>

6.好了,现在可以新建个example来测试一下了~
1)controllers\example.php

<?php
class Example extends Controller {

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

        // $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
    }

    function index()
    {
        // This example is taken from the Smarty demo and modified slightly
        $this->assign("Name","Fred Irving Johnathan Bradley Peppergill");
        $this->assign("FirstName",array("John","Mary","James","Henry"));
        $this->assign("LastName",array("Doe","Smith","Johnson","Case"));
        $this->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"), array("I", "J", "K", "L"), array("M", "N", "O", "P")));

        $this->assign("contacts", array(array("phone" => "555-1234", "fax" => "555-2345", "cell" => "999-9999"), array("phone" => "555-4444", "fax" => "555-3333", "cell" => "888-8888")));

        $this->assign("state_values", array( 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY' ));
        $this->assign("state_output", array( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ));

        // english is the default if you don't set lang
        $this->assign("lang", "english");

        // Set the validation rules if this is a submit
        if ( $this->input->post('action') == 'submit' )
        {
            $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
            $this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
            $this->form_validation->set_rules('state', 'State', '');

            if ( ! $this->form_validation->run() )
            {
                $data['error'] = 'Check and fix the form errors below';
            }
            else
            {
                $data['message'] = 'Thanks for posting!';
            }
        }

        // These assignments are passed by the associative array
        $data['title'] = 'Welcome to the Smarty Website';
        $data['bold'] = true;
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARTDED_FOR'] != '') {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
        }
        $data['ip_address'] = $this->input->server('REMOTE_ADDR');
        //$data['ip_address'] = $ip_address;
        // Calling the convenience function view() that allows passing data
        //$this->smarty->view( 'example.tpl', $data );
        $this->display( 'example.tpl', $data );
    }
}

2)views\templates\example.tpl

{include file="header.tpl" title="Example Smarty Page" name="$Name"}

<h1>
{if $bold}<b>{/if}
{* capitalize the first letters of each word of the title *}
Title: {$title|capitalize}
{if $bold}</b>{/if}
</h1>

{if $error != ''}<p class="error">{$error}</p>{/if}
{if $message != ''}<p class="message">{$message}</p>{/if}

{ci_config name="base_url"}
<p>The configuration value of base_url is <em>{$base_url}</em></p>

<p>The current date and time is <em>{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}</em></p>

<p>The value of global assigned variable $SCRIPT_NAME is <em>{$SCRIPT_NAME}</em></p>

<p>The value of server environment variable SERVER_NAME is <em>{$smarty.server.SERVER_NAME}</em></p>

<p>The value of your IP address is: <em>{$ip_address}</em></p>

<p>The value of {ldelim}$Name{rdelim} is <em>{$Name}</em></p>

<p>The value of {ldelim}$Name|upper{rdelim} is <em>{$Name|upper}</em></p>

<h2>An example of a section loop:</h2>
<ul>
{section name=outer loop=$FirstName}
{if $smarty.section.outer.index is odd by 2}
    <li>{$smarty.section.outer.rownum} . {$FirstName[outer]} {$LastName[outer]}</li>
{else}
    <li>{$smarty.section.outer.rownum} * {$FirstName[outer]} {$LastName[outer]}</li>
{/if}
{sectionelse}
    <li>none</li>
{/section}
</ul>

<h2>An example of section looped key values:</h2>
{section name=sec1 loop=$contacts}</li>
<ul>
    <li>phone: {$contacts[sec1].phone}</li>
    <li>fax: {$contacts[sec1].fax}</li>
    <li>cell: {$contacts[sec1].cell}</li>
</ul>
{/section}

<h2>An example testing strip tags:</h2>
{strip}
<table border=0>
    <tr>
        <td>
            <a HREF="{$SCRIPT_NAME}">
            <font color="red">This is a  test     </font>
            </a>
        </td>
    </tr>
</table>
{/strip}


<h2>An example of the html_select_date function:</h2>

<form>
{html_select_date start_year=1998 end_year=2010}
</form>

<h2>An example of the html_select_time function:</h2>

<form>
{html_select_time use_24_hours=false}
</form>

<h2>An example using form_validation:</h2>

{* the following line loads system/languages/$lang/label_lang.php *}
{ci_language file="label" lang="$lang"}
<form action="#" method="post">
<fieldset>
    <label for="username">{ci_language line="username"}:</label>
    <input type="text" name="username" id="username" value="{ci_form_validation field='username'}" /><br />
    {ci_form_validation field='username' error='true'}

    <label for="password">{ci_language line="password"}:</label>
{*
   Note: Can't use ci_form_validation to set the value for password
         because it is encrypted during validation.
*}
    <input type="password" name="password" id="password" value="" /><br />
    {ci_form_validation field='password' error='true'}

    <label for="passconf">{ci_language line="passconf"}:</label>
    <input type="password" name="passconf" id="passconf" value="" /><br />
    {ci_form_validation field='passconf' error='true'}

    <label for="email">{ci_language line="email"}:</label>
    <input type="text" name="email" id="email" value="{ci_form_validation field='email'}" /><br />
    {ci_form_validation field='email' error='true'}

    {ci_form_validation field='state' assign='selected_state'}
    <label for="state">{ci_language line="state"}:</label>
    <select name='state'>
    {html_options values=$state_values output=$state_output selected=$selected_state}
    </select><br />
    {ci_form_validation field='states' error='true'}

    <input type="submit" name="action" value="submit" />
</form>

{include file="footer.tpl"}

views\templates\header.tpl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 
 
<head> 
    <title>{$title} - {$name}</title> 
    <meta http-equiv="content-type" content="application/xhtml+xml;charset=utf-8" /> 
    <style type="text/css">
    {literal}
        body {background-color: #fff; color: #000; width: 800px; font-family: 'courier', 'courier new', monotype;}
        h1, h2 {background-color: #fff; color: #999; font-family:"Times New Roman",Georgia,serif;}
        h1 {font-size: 2em;}
        h2 {font-size: 1.5em;}
        em {border: solid #000 1px; padding: 0 5px; font-style: normal;}
        .error {background-color: #ff0; color: #c00;}
        .message {background-color: #fff; color: #0c0;}
    {/literal}
    </style>
</head> 
<body>

views\templates\footer.tpl

</body>
</html>

附:

1)附件 中的language\english\label_lang.php是例子所用,并不是配置所需

2) 例子中发现会有notie报错,这种无害的error提示可以关掉 详见 CodeIgniter中的Error

3)url中要写index.php\example 比较不爽 可以 去掉php框架CI默认url中的index.php


参考:http://www.coolphptools.com/codeigniter-smarty

  

  

原文地址:https://www.cnblogs.com/cuoreqzt/p/2997769.html