簡體   English   中英

PHP Smarty 將包含動態插入 Smarty 模板

[英]PHP Smarty dynamically insert an include into a Smarty template

我正在使用的系統從數據庫中獲取一串 HTML 並將其傳遞給 smarty,如下所示:

$smarty->assign('content', $content);
$smarty->display($template);

所以沒什么好看的。 他們現在想要添加動態包含,其中將包含一個基於他們通過所見即所得添加的字符串的組件。 例如:

[[latest-slider]]

會翻譯成

{include file='components/latest-slider.tpl'}

字符串替換沒有問題,因為我只是對文本進行正則表達式並適當地替換它。 現在,在顯示 output 時,Smarty 只是將其視為一個字符串,它沒有注意到它是 smarty 代碼並且不解析它的事實。

我嘗試使用 Smarty fetch()獲取已編譯的模板,然后對其進行正則表達式替換和eval() 但是,這不是我可以 go 向下的路徑,因為它無法解析它,因為它不再看到任何{literally}標簽。 主要是圍繞 Google Analytics 代碼並落在Smarty Compiler: Syntax error in template

你能做如下的事情嗎

PHP:

$component = preg_replace(/some regex/, 'replacement', $content);
$smarty->assign('component', 'components/'.$component.'.tpl');

$smarty->assign('content', $content);
$smarty->display($template);

TPL $template

{include file=$component}

更好的方法是使用 smarty 過濾器 output。

$smarty->registerFilter("pre", 'myFunc');

function myFunc($tpl_output)
{
   $tpl_output = str_replace('[[latest-slider]]', '{include file='components/latest-slider.tpl'}', $tpl_output);

   //or regex: $tpl_output = preg_replace('/some regex/', 'replace', $tpl_output);
   return $tpl_output;
}

這將在獲取頁面以進行 smarty 渲染之前替換 [[latest-slider]]。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM