2016-02-14 49 views
2

有一个textarea这里用户可以编辑一些模板,可以使用变量,如:Yii2使数据库内容

{{model.user.name}} 

应用需要数据和显示HTML输出替换此变量。

我们可以写一个小功能,这将影响数据的模板替换变量,但我们需要使用模板引擎就像嫩枝或Smarty的。

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

现在我们可以从Smarty的或嫩枝使用视图解析器。

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

但我看到这个错误:

Unable to find template "template.twig" (looked into: .). 

如何使用Smarty的或嫩枝呈现从数据库中Yii2内容的模板?

回答

1

我发现胡须(https://github.com/bobthecow/mustache.php)和我使用的是这样的:

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

你在正确的轨道上 - 看到https://github.com/yiisoft/yii2/issues/7309 - 胡子最适合你的使用情况。干杯:) – jacmoe

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扩展处理模板。

然后,所有你需要做的就是调用呈现在你的控制器动作时添加.twig扩展:

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

然后把你的树枝模板中查看文件夹,其中的意见通常去。

阅读树枝延伸的文档:Twig Extension for Yii 2

如果你只想用树枝模板,就可以避免指定扩展名(.twig)如果你设置了默认的扩展:

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

最后我需要呈现来自数据库,而不是文件内容的字符串。我为我的问题找到了一个解决方案,小胡子。 – daniftodi

+0

不够公平 - 你可以用枝条或任何你喜欢 - 我似乎误解你问什么。 ;) – jacmoe

0

您应该创建一个twig分量会环绕Twig_Environment。如果需要,您可以添加yii\twig\Extension扩展名。如果你真的需要渲染从一个字符串变量,你可以实现你自己的Twig_LoaderInterface模板

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

:那你应该这样使用它。有Twig_Loader_String,但它已被弃用,你不应该使用它。