如何在Smarty3中显示PHP变量中模板的一部分


How to display in Smarty3 part of template which is in a PHP variable?

我正在处理一项任务,该任务的一部分由其他人完成。所以我在数据库中有一些文本,需要把它们添加到现有的模板中。问题是,文本包含一些变量,我想显示这些变量(它们被提供给模板)。现在我只能看到大括号和里面的变量名,而不能看到它的值。

PHP:

$var = "{$rest_name} offers good {$cuisine} food.";
$smarty->assign("rest_name", "My Rest");
$smarty->assign("cuisine", "thai");
$smarty->assign("desc", $var);

TPL:

{$desc}

显示{$rest_name} offers good {$cuisine} food.,但我想在那里看到My Rest offers good thai food.

我无法在PHP中做到这一点,因为应用程序的不同部分传递数据,所以唯一知道一切的地方就是模板。

如何强制Smarty将PHP变量作为模板的一部分呈现?

{$rest_name} offers good {$cuisine} food.的PHP中,首先需要使用单引号。否则,您会收到未定义变量的警告,因此PHP中正确的代码是:

$var = '{$rest_name} offers good {$cuisine} food.';
$smarty->assign("rest_name", "My Rest");
$smarty->assign("cuisine", "thai");
$smarty->assign("desc", $var);

在Smarty中,您可以使用:

{include file="string:$desc"}

它将立即显示解析后的字符串。

您可以使用将其分配给变量

{include file="string:$desc" assign="assigned"}
some other stuff here
{$assigned}

在这两种情况下,你都会得到你想要的输出:

My Rest提供美味的泰国菜。