Yii2呈现数据库内容

时间:2016-02-14 07:46:53

标签: yii2 twig smarty render

有一个textarea,用户可以编辑一些模板,并可以使用如下变量:

String [] words = {i, to , go , eat,know , i ,let , let , figure , eat};
Map <String,Integer> set=new HashMap();
for (String w:words)
{
  if (set.get(w)==null)
  {
     set.put(w,1)
  }
else
     set.put(w,set.get(w)+1) 
 }

应用程序需要用数据替换这些变量并显示HTML输出。

我们可以编写一个小函数来替换模板中的变量和数据,但我们需要使用像Twig或Smarty这样的模板引擎。

https://github.com/yiisoft/yii2-twig https://github.com/yiisoft/yii2-smarty

现在我们可以使用Smarty或Twig的ViewRenderer。

{{model.user.name}}

但是我看到了这个错误:

$render = new ViewRenderer();
$content = $render->render($this->view,'template.twig',[
       'model' => $model,
]);

如何使用Smarty或Twig在Yii2中使用数据库中的内容呈现模板?

3 个答案:

答案 0 :(得分:1)

我找到了胡子(https://github.com/bobthecow/mustache.php),我正在使用这样:

$m = new \Mustache_Engine();
echo $m->render("Hello {{model.client.firma}}",['model' => $model]);

答案 1 :(得分:0)

您没有手动创建渲染器,您可以配置应用程序组件,如下所示:

[
    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => ['html' => '\yii\helpers\Html'],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
]

您告诉Yii,有一个渲染器可以处理扩展名为.twig的模板。

然后,您需要做的就是在控制器操作中调用render时添加.twig扩展名:

public function actionIndex()
{
        return $this->render('index.twig');

然后将您的树枝模板放在视图通常位于的视图文件夹中。

阅读树枝扩展程序的文档:Twig Extension for Yii 2

如果您只想使用树枝模板,则可以避免在设置默认扩展名时指定扩展名(.twig):

'components' => [
    'view' => [
        'defaultExtension' => 'twig',

答案 2 :(得分:0)

您应该创建一个twig组件,它将包裹Twig_Environment。如果需要,您可以添加yii\twig\Extension扩展名。然后你应该像这样使用它:

$renderedTemplate = Yii::$app->twig->render($template, $context);

如果您确实需要从字符串变量渲染模板,则可以实现自己的Twig_LoaderInterface。有一个Twig_Loader_String,但它已被弃用,您不应该使用它。

相关问题