[精讚] [會員登入]
1878

[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

你可能感興趣的文章

使用strcmp來判斷日期是否介於某日期之間 要比較現在日期是否在兩個日期之間,使用字串比對的方法

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

[PHP] 檢查IP是否在某個網段內 mtachcidr 要檢查IP是否在某個網段內,要寫幾行?10行?5行? 不用,只要2行。以下是我寫的 code /** * matchCI

使用Yahoo OAuth2 1/2 使用Yahoo OAuth2來認證我的網站

使用Yahoo OAuth2 2/2 使用Yahoo OAuth2認證我的網頁

PHP程式經驗 #2 -- print和echo的差異 常在寫php的人一定會想知道echo和print這兩個函數有什麼不一樣 驗證 1. 比較print 和echo 函式的執

隨機好文

使用Google尋找你的手機 這近發現google竟然可以用來找android的手機,而且不需要經過什麼設定或安裝軟體。

UTF-8 BOM (Byte Order Mark) 的問題 在 Michael Kaplan 那看到 Every character has a story #4: U+feff

SELinux 常用指令和檔案 在Redhat系列中,Centos5以後加入了selinux,他並沒有這麼可怕,不必每次看到Selinux ,就想把他

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

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