[精讚] [會員登入]
1996

[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

你可能感興趣的文章

[PHP8] 使用autoload autoload+ namespace +use 到了php7之後,namespace和use越來越重要,此篇整理autoload和namespace、use的結合使用。

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

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

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

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

利用 php 木馬作為駭客攻擊的手法 利用 php 木馬作為駭客攻擊的手法

隨機好文

HP SAS硬碟leds燈號說明 HP SAS硬碟leds燈號(hp g7/g6系統適用)說明

沒有非誰做不可的事,也沒有不可被取代的人 沒有非誰做不可的事,也沒有不可被取代的人

魔球中小女孩唱的歌 The show 魔球中小女孩唱的歌 The show

問問題 問問題其實內涵很深,我悟了很久才懂。 有人問題的目的並不一定是想要得到答案,有時只是純粹想問問題..

讓radio box 或checkbox 好按 在行動裝置下,radio box及checkbox變得很難按得到