简体   繁体   中英

PHP Smarty dynamically insert an include into a Smarty template

The system I'm working with gets a string of HTML from a database and passes it down to smarty like so:

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

So nothing fancy. They now want to add dynamic includes which will include a component based on a string that they add via the WYSIWYG. For example:

[[latest-slider]]

Would translate to

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

The string replace is no problem as I just regex over the text and replace it appropriately. Now when it comes to displaying the output Smarty simply sees this as a string, it doesn't notice the fact it's smarty code and doesn't parse it.

I tried getting the complied template with Smarty fetch() and then do the regex replace and eval() on it. However, this is not a path I can go down as it fails to parse it because it no longer sees any of the {literally} tags. The main one being around the Google Analytics code and falls over Smarty Compiler: Syntax error in template .

Can you do something like the following

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}

Better way is use smarty filter 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;
}

This will replace [[latest-slider]] before page is fetch for smarty render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM