wodrow 2015-12-24 11:30:18 12092次浏览 8条评论 1 1 0

smarty模板安装教程详见yii2集成smarty;
最新版smarty默认在模板中不能使用php原生函数,在模板文件中会产生许多的不便,查看文档得知如果要使用php原生语句必须用SmartyBC类,解决方案:

/vender/yiisoft/yii2-smarty/ViewRenderer.php中找到use Smarty;改为use SmartyBC as Smarty;;

使用效果:

test
{php}
echo "123456789";
{/php}

浏览器输出
test 123456789

当然修改vender里的内容并不是最好的解决方案,如有大神能提供更好的解决方案,希望可以分享出来

觉得很赞
  • 评论于 2015-12-24 11:47 举报

    不知道能不能使用smarty的老版本,可以用composer安装smarty老版本试试

  • 评论于 2015-12-24 14:42 举报

    研究出了更好的解决办法了

    Smarty - 模板引擎中文参考手册中有一个php处理变量:$php_handling
    该变量告诉Smarty怎样处理嵌入到模版中的php代码.有四种可能的设置,默认为SMARTY_PHP_PASSTHRU

    SMARTY_PHP_PASSTHRU - Smarty echos tags as-is.Smarty
    原样输出标记.
    
    SMARTY_PHP_QUOTE - Smarty quotes the tags as html entities.Smarty
    作为html实体引用标记
    
    SMARTY_PHP_REMOVE - Smarty removes the tags from the templates.Smarty
    从模板中移出标记.
    
    SMARTY_PHP_ALLOW - Smarty will execute the tags as PHP code.Smarty
    将作为php代码执行标记.
    

    在smarty类里可以看到他们对应的值分别为0,1,2,3
    所以只需在配置文件中配置

    return [
        'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
        'components' => [
            'cache' => [
                'class' => 'yii\caching\FileCache',
            ],
            /* add */
            'view' => [  
                'renderers' => [  
                    'tpl' => [  
                        'class' => 'yii\smarty\ViewRenderer',  
                        'cachePath' => '@runtime/Smarty/cache',  
    		    'compilePath' => '@runtime/Smarty/compile',
    		    'options' => [
    			'php_handling'=>3,
                        ],
                    ],  
                ],  
            ],
            /* end */
        ],
    ];
    

    即可使用原生的php

  • 评论于 2015-12-24 14:47 举报

    不过还是需要继承SmartyBC类

    觉得很赞
  • 评论于 2015-12-24 18:42 举报

    不知道能不能使用smarty的老版本,可以用composer安装smarty老版本试试

  • 评论于 2016-03-09 23:21 举报

    // 请教一个问题 YII整合了Smarty 然后输出的时间
    // 模板里面的时间是不变的 但是PHP赋值的时间已经变了

    $abc = date("Y-m-d H:i:s",time());
    echo $abc;//这个时间已经变化了
    

    //模板输出的时间 还是最早的那个时间 没有任何变化

    $this->smarty->assign('abc',$abc);
    $this->smarty->display('index/index.html');
    
    1 条回复
    评论于 2016-03-23 17:22 回复

    我刚才特意试了这个问题,不存在的,可能是你smarty设置缓存时间了。你确认下。

  • 评论于 2016-03-23 17:23 举报

    用了楼主的方法,不过还有一些问题的。比如 在模板里使用 use语句,就会报异常。基本的php语句还是可以解析的。

  • 评论于 2016-03-23 18:17 举报

    smarty使用函数的形式来解析视图文件

    function funname($view){
        ...
        return $viewout;
    }
    

    自然不能识别namespace,use等关键字
    可以用\Yii::,\common\models\LoginForm等代替

  • 评论于 2016-11-14 14:28 举报

    yii2 整合smarty 'cachePath' => '@runtime/Smarty/cache' 但是 没有生成cache文件 为啥?

您需要登录后才可以评论。登录 | 立即注册