如何在 yii2 中显示来自字符串的 smarty 模板?

How show smarty template from string in yii2?


我想在 yii2 中使用 smarty 模板引擎。
在我的项目中,我需要从数据库加载视图代码并从控制器渲染它们。

我的问题是:

有什么方法可以从字符串渲染视图代码并像普通渲染一样控制它吗?

我需要如下内容:

$this->renderAsString($templateStr, ['param1'=>$val1, 'param2'=>$val2]);

这对我来说很重要,我可以访问 index.tpl 文件中的变量和函数,如下面的代码。

$this->render('index.tpl'['param1'=>$val1, 'param2'=>$val2]);

我读过这个 http://www.smarty.net/docs/en/resources.string.tpl 但我认为我的答案不同。

有一个名为 yii2-smarty 的特殊单独扩展,用于使用 Smarty 渲染视图。您需要通过 Composer 安装它,然后像这样配置使用:

return [
    //....
    'components' => [
        'view' => [
            'renderers' => [
                'tpl' => [
                    'class' => 'yii\smarty\ViewRenderer',
                    //'cachePath' => '@runtime/Smarty/cache',
                ],
            ],
        ],
    ],
];

具体你的问题,看Github上的这两个问题:

核心开发人员 Klimov Paul 推荐使用 eval,但在 Smarty 中也存在专门用于此类情况的功能。

示例 8.4。另一个 {eval} 例子

This outputs the server name (in uppercase) and IP. The assigned variable $str could be from a database query.

<?php
$str = 'The server name is {$smarty.server.SERVER_NAME|upper} '
       .'at {$smarty.server.SERVER_ADDR}';
$smarty->assign('foo',$str);
?>

Where the template is:

{eval var=$foo}