[精讚] [會員登入]
1982

[Smarty5] 如何在樣版中使用php本身的函式

解決 smarty5版後不能直接叫用 php函式的問題

分享此文連結 //n.sfs.tw/16438

分享連結 [Smarty5] 如何在樣版中使用php本身的函式@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2024-07-07 07:11:06 最後編修
2024-07-06 18:36:28 By 張○○
 

自動目錄

是這樣的,這次在 smart5 中要使用php原本的函式,像這樣:

One.tpl

  <h5>{{rand()}}</h5>

 

在 smarty4以前都沒有問題,但這次在 smarty5 的環境中卻出錯了:

Smarty\CompilerException

Syntax error in template "file:One.mtpl" on line 16 "<h5>{{rand()}}</h5>" unknown modifier 'rand'

沒錯,無法使用php的內建函數。

官網提出的解釋是因為資安弱點,所以爾後得使用modifier,不再提供樣版中直接使用php函式的功能。

後來找了一些資料[2],發現以前的函式 register_modifier() 也不能用(這是舊版用的),在 smarty5 中你可以使用registerPlugin()函式來註冊新的modifier就可以了。

$smarty->registerPlugin('modifier', 'rand', 'rand');

參數三個分別是 type、在樣版中的名稱、實際叫用的函式名稱(也可以使用你自己的函式)。

這樣就可以在樣版中使用php的函式了。

會在樣版中使用的函式就那幾個,所以也可以寫在初始化設定中,例如我寫成這樣:

parent::registerPlugin('modifier', 'lang', 'lang');

* lang() 是自定義的函數

上面的parent 是因為繼承smarty的物件,完整大概長這樣:

use Smarty;

class Smarty5 extends Smarty\Smarty {

    public function __construct()
    {
        parent::__construct();
        parent::setTemplateDir(APPPATH . 'Views/');
        parent::setConfigDir(APPPATH . 'Config/Smarty5/');
        parent::setCompileDir(WRITEPATH . 'templates_c/')->setCacheDir(WRITEPATH . 'cache/');
        parent::setLeftDelimiter('{{');
        parent::setRightDelimiter('}}');
        parent::registerPlugin('modifier', 'lang', 'lang');
    }

    public function view($tpl_name) {
        parent::display($tpl_name);
    }
}

這樣我就可以使用

$s= new Smarty5();

這樣的方法叫用 smarty了。

 

參考資料

[1] smarty5官網 https://smarty-php.github.io/smarty/stable/upgrading/#variable-scope-bubbling

[2] https://github.com/smarty-php/smarty/issues/813

END

你可能感興趣的文章

PHP判斷對方瀏覽器語系 多語系的網頁應該主動偵查瀏覽器的語系,配合使用者跳出合適的語系。

[PHP>7.3] switch中的 Did you mean to use "continue 2"? 除錯 這近更新 PHP到7.3版以後,出現這樣的錯:targeting switch is equivalent to "break". Did you mean to use "continue 2"?解決方法

設定Google analytics API #1 -- Google網站上的設定 讓你的網站能夠存取你的Google analytics上面的資料

PHP 產生連續的日期 要用PHP產生連續的日期,連續月份

[CodeIgniter 3] 修改或插入資料時遇到函數的處理 CI3 中要新增或修改的資料中如果有 now()這類的函數,要怎麼處理?

PHP 移除陣列中的元素 要移除陣列中的其中一項元素

隨機好文

[jQuery] 利用load()來達成ajax的寫法 jQuery中利用load()來達成ajax的寫法,也有人稱他是假的ajax,作法就是..

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

[AS3] 我做的唯一一個Flash As3遊戲UFO INVADSION [AS3] 我做的唯一一個Flash As3遊戲,是第一個也是最後一個,後來就沒再寫as3,不過as3還滿好玩的。

[CodeIgniter 3] 資料庫的使用方法整理2/2 CI3 承襲 CI2,有很多的builder class可以用,依各人的使用習慣,有人喜歡一堆sql字串,有人喜歡用helper