Renderpartial In Console

This always bewildered me my why you couldn’t have renderPartial from the ConsoleCommands, I ran into this issue with trying to generate emails from view files.

Anyway here is a workaround I created by extending the CConsoleCommand




<?php

class ConsoleCommand extends CConsoleCommand

{

    /**

     * Based on the CWebApplication

     * @see CWebApplication::getViewPath

     * @return string

     */

    public function getViewPath()

    {

        return Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'views';

    }


    /**

     * Modified copy of getViewFile

     * @see CController::getViewFile

     * @param $viewName

     * @return string

     */

    public function getViewFile($viewName)

    {

        return $this->getViewPath().$viewName.'.php';

    }


    /**

     * Modeified copy of renderPartial from CController

     * @see CController::renderPartial

     * @param $view

     * @param $data

     * @param $return

     * @return mixed

     * @throws CException

     */

    public function renderPartial($view, $data, $return)

    {

        if(($viewFile=$this->getViewFile($view))!==false)

        {

            $output=$this->renderFile($viewFile,$data,true);

            if($return)

                return $output;

            else

                echo $output;

        }

        else

            throw new CException(Yii::t('yii','{class} cannot find the requested view "{view}".',

                array('{class}'=>get_class($this), '{view}'=>$view)));

    }

}