View provides a set of methods (e.g. [[render()]]) for rendering purpose.
View is configured as an application component in Application by default.
You can access that instance via Yii::$app->view.
You can modify its configuration by adding an array to your application config under components
as it is shown in the following example:
~~~
'view' => [
'theme' => 'app\themes\MyTheme',
'renderers' => [
you may add Smarty or Twig renderer here
]
...
]
~~~
/** * Adds an asset to the view * * @param View $view The View object * @param string $file The asset file name * @param string $type The asset file type (css or js) * @param string $class The class name of the AssetBundle * * @return void */ protected function addAsset($view, $file, $type, $class) { if ($type == 'css' || $type == 'js') { $asset = $view->getAssetManager(); $bundle = $asset->bundles[$class]; if ($type == 'css') { $bundle->css[] = $file; } else { $bundle->js[] = $file; } $asset->bundles[$class] = $bundle; $view->setAssetManager($asset); } }
/** * * @param View $view * @param array $data */ public static function bizConfig($view, $config = [], $position = View::POS_BEGIN) { $default = ['delay' => 1000, 'limit' => 20, 'checkStock' => false, 'debug' => YII_ENV == 'dev', 'pullUrl' => \yii\helpers\Url::to(['/master/sources/pull'])]; $js = "\n var biz = biz || {};" . "\n biz.config = " . Json::encode(ArrayHelper::merge($default, $config)) . ";\n"; $view->registerJs($js, $position); BizAsset::register($view); }
/** * @param string $language * @param View $view */ public function registerLanguage($language, $view) { if (file_exists($this->sourcePath . "/locale/{$language}.js")) { $this->js = array_merge($this->js, ['min/locales.min.js']); $view->registerJsFile($this->baseUrl . "/locale/{$language}.js"); $js = <<<JS moment.locale('{$language}'); JS; $view->registerJs($js, View::POS_READY, 'moment-locale-' . $language); } }
/** * Registers the CSS and JS files with the given view. * @param \yii\web\View $view the view that the asset files are to be registered with. */ public function registerAssetFiles($view) { $manager = $view->getAssetManager(); foreach ($this->css as $css) { $view->registerCssFile($manager->getAssetUrl($this, $css), $this->cssOptions); } $view->registerJsFile($this->basketJs); $jsFiles = []; foreach ($this->js as $js) { $jsFiles[] = Json::encode(['url' => $manager->getAssetUrl($this, $js)]); } $view->registerJs(sprintf('basket.require(%s);', implode(",\r\n", $jsFiles)), View::POS_END); }
/** * @param View $view */ public function applyTo(View $view) { $attributes = $this->getAttributes(null, ['id', 'meta_id']); foreach ($attributes as $name => $value) { $view->registerMetaTag(['property' => 'twitter:' . $name, 'content' => $value]); } }
/** * Initializes plugin * @param View $view * @return $this */ public function initPlugin(View $view, $options = []) { $options = array_merge(['message' => Yii::t('mgcode/sessionWarning', 'Your session is going to expire at {time}.')], $options); $json = Json::encode($options); $view->registerJs("\$('#session-warning-modal').sessionWarning({$json});"); return $this; }
public function sendMessage($to, $file, $params = []) { $view = new View(); $message = ['from' => $this->from, 'to' => $to, 'to' => '+8618670366212', 'text' => $view->render($file, $params)]; return; //@todo remove $this->getTransport()->send($message); }
/** * Register global meta tags like verifications and so on * * @param View $view */ protected static function registerGlobalMetaTags($view) { $globalMetaTags = Yii::$app->cache->get('__globalMetaTags'); if ($globalMetaTags === false) { $globalMetaTags = GlobalMetaTag::find()->andWhere(['active' => 1])->asArray()->all(); Yii::$app->cache->set('__globalMetaTags', $globalMetaTags, 3600 * 24); } foreach ($globalMetaTags as $globalTag) { $view->registerMetaTag(['name' => $globalTag['name'], 'content' => $globalTag['content']], $globalTag['name']); } }
/** * @param \yii\web\View $view * @throws \yii\base\InvalidConfigException If file with the locale is not exists. */ public function registerLocaleInternal($view) { $localeFilePath = $this->tryFindLocale(); if (YII_DEBUG && !$localeFilePath) { throw new InvalidConfigException('Locale file "' . \Yii::$app->language . '" not exists!'); } $manager = $view->getAssetManager(); $view->registerJsFile($manager->getAssetUrl($this, $this->locale), $this->jsOptions, 'moment-locale-' . $this->locale); if ($this->setLocaleOnReady) { $js = "moment().locale('" . $this->locale . "');"; $view->registerJs($js, View::POS_READY, 'moment-set-default-locale'); } }
/** * @param \yii\web\View $view * @throws \yii\base\InvalidConfigException If file with the locale is not exists. */ public function registerLocaleInternal($view) { $localeFile = strtolower($this->locale) . '.js'; $localeFilePath = "{$this->sourcePath}/{$localeFile}"; if (YII_DEBUG && !file_exists($localeFilePath)) { throw new InvalidConfigException('Locale file "' . $localeFilePath . '" not exists!'); } $manager = $view->getAssetManager(); $view->registerJsFile($manager->getAssetUrl($this, $localeFile), $this->jsOptions, 'moment-locale-' . $this->locale); if ($this->setLocaleOnReady) { $js = "moment.locale('{$this->locale}');'"; $view->registerJs($js, View::POS_READY, 'moment-set-default-locale'); } }
/** * @throws \rmrevin\yii\minify\Exception */ public function init() { parent::init(); $minify_path = $this->minify_path = (string) \Yii::getAlias($this->minify_path); if (!file_exists($minify_path)) { helpers\FileHelper::createDirectory($minify_path); } if (!is_readable($minify_path)) { throw new Exception('Directory for compressed assets is not readable.'); } if (!is_writable($minify_path)) { throw new Exception('Directory for compressed assets is not writable.'); } if (true === $this->compress_output) { \Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function (\yii\base\Event $Event) { /** @var \yii\web\Response $Response */ $Response = $Event->sender; if ($Response->format === \yii\web\Response::FORMAT_HTML) { if (!empty($Response->data)) { $Response->data = HtmlCompressor::compress($Response->data, $this->compress_options); } if (!empty($Response->content)) { $Response->content = HtmlCompressor::compress($Response->content, $this->compress_options); } } }); } }
public function renderFile($viewFile, $params = [], $context = null) { if ($this->theme == null) { $this->setTheme(); } return parent::renderFile($viewFile, $params, $context); }
/** * @param View $view * @return static the registered asset bundle instance */ public static function register($view) { $configOptions = []; $configSelector = self::DEFAULT_SELECTOR; try { $thisBundle = \Yii::$app->getAssetManager()->getBundle(__CLASS__); $configOptions = $thisBundle->options; $configSelector = $thisBundle->selector; } catch (\Exception $e) { // do nothing... } $options = empty($configOptions) ? '' : Json::encode($configOptions); if ($configSelector !== self::DEFAULT_SELECTOR) { $view->registerJs(' hljs.configure(' . $options . '); jQuery(\'' . $configSelector . '\').each(function(i, block) { hljs.highlightBlock(block); });'); } else { $view->registerJs(' hljs.configure(' . $options . '); hljs.initHighlightingOnLoad();', View::POS_END); } return parent::register($view); }
/** * Registers the CSS and JS files with the given view. * @param \yii\web\View $view the view that the asset files are to be registered with. */ public function registerAssetFiles($view) { if ($this->configuration !== null) { $view->registerJs('NProgress.configure(' . Json::encode($this->configuration) . ');'); } $view->registerJs(<<<JS jQuery(document).on('pjax:start', function() { NProgress.start(); }); jQuery(document).on('pjax:end', function() { NProgress.done(); }); JS ); $view->registerJs(<<<JS var exceptUrls = [ ]; jQuery(document).on('ajaxSend', function(e, xhr, options) { if( \$.inArray( options.url, exceptUrls ) == -1) NProgress.start(); }); jQuery(document).on('ajaxComplete', function(e, xhr, options) { if( \$.inArray( options.url, exceptUrls ) == -1 ) NProgress.done(); }); JS ); parent::registerAssetFiles($view); }
/** * Register scripts * @param View $view */ protected function registerScripts(\yii\web\View $view) { if ($this->clientOptions !== false) { $options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions); $js = "jQuery('#{$this->id}').fancybox({$options});"; $view->registerJs($js, View::POS_READY); } }
/** * @param View $view * @param KursExtended $kursRecord * @param mixed $tip * @return string */ function renderRazdelyTipa($view, $kursRecord, $tip) { $ret = ''; $query = $kursRecord->getRazdelyKursaRel()->orderBy('nomer')->where(['tip' => TipRazdelaKursa::asSql($tip)]); foreach ($query->all() as $razdelRecord) { $ret .= $view->render('_razdel-kursa', compact('razdelRecord')); } return $ret; }
/** * Registers JS code to help initialize Select2 widgets * with access to netis\crud\crud\ActiveController API. * @param \yii\web\View $view */ public static function registerSelect($view) { $script = <<<JavaScript (function (s2helper, \$, undefined) { "use strict"; s2helper.formatResult = function (result, container, query, escapeMarkup, depth) { if (typeof depth == 'undefined') { depth = 0; } var markup = []; window.Select2.util.markMatch(result._label, query.term, markup, escapeMarkup); return markup.join(""); }; s2helper.formatSelection = function (item) { return item._label; }; // generates query params s2helper.data = function (term, page) { return { search: term, page: page }; }; // builds query results from ajax response s2helper.results = function (data, page) { return { results: data.items, more: page < data._meta.pageCount }; }; s2helper.getParams = function (element) { var primaryKey = element.data('relation-pk'); if (typeof primaryKey === 'undefined' || primaryKey === null) { primaryKey = 'id'; } var params = {search: {}}; params.search[primaryKey] = element.val(); return params; }; s2helper.initSingle = function (element, callback) { \$.getJSON(element.data('select2').opts.ajax.url, s2helper.getParams(element), function (data) { if (typeof data.items[0] != 'undefined') { callback(data.items[0]); } }); }; s2helper.initMulti = function (element, callback) { \$.getJSON(element.data('select2').opts.ajax.url, s2helper.getParams(element), function (data) {callback(data.items);}); }; }( window.s2helper = window.s2helper || {}, jQuery )); JavaScript; $view->registerJs($script, \yii\web\View::POS_END, 'netis.s2helper'); \maddoger\widgets\Select2BootstrapAsset::register($view); }
/** * Registers plugin events * * @param View $view The View object */ protected function registerPluginEvents($view) { if (!empty($this->pluginEvents)) { $id = 'jQuery("#' . $this->options['id'] . '")'; $js = []; foreach ($this->pluginEvents as $event => $handler) { $function = new JsExpression($handler); $js[] = "{$id}.on('{$event}', {$function});"; } $js = implode("\n", $js); $view->registerJs($js); } }
/** * @throws \rmrevin\yii\minify\Exception */ public function init() { parent::init(); if (php_sapi_name() !== 'cli') { $urlDetails = \Yii::$app->urlManager->parseRequest(\Yii::$app->request); if (in_array($urlDetails[0], $this->exclude_routes)) { $this->enableMinify = false; } } $minify_path = $this->minify_path = (string) \Yii::getAlias($this->minify_path); if (!file_exists($minify_path)) { helpers\FileHelper::createDirectory($minify_path); } if (!is_readable($minify_path)) { throw new Exception('Directory for compressed assets is not readable.'); } if (!is_writable($minify_path)) { throw new Exception('Directory for compressed assets is not writable.'); } if (true === $this->compress_output) { \Yii::$app->response->on(\yii\web\Response::EVENT_BEFORE_SEND, function (\yii\base\Event $Event) { /** @var \yii\web\Response $Response */ $Response = $Event->sender; if ($Response->format === \yii\web\Response::FORMAT_HTML) { if (!empty($Response->data)) { $Response->data = HtmlCompressor::compress($Response->data, ['extra' => true]); } if (!empty($Response->content)) { $Response->content = HtmlCompressor::compress($Response->content, ['extra' => true]); } } }); } }
/** * Imposta il titolo della pagina secondo i seguenti criteri: * <ul> * <li>Se la proprietà <code>$pageTitle</code> non è impostata viene utilizzato il parametro * <code>'title'</code> dell'applicazione. Se nemmeno quest'ultimo è impostato viene sollevata * un'eccezione.</li> * <li>Se la proprietà <code>$pageTitle</code> è assegnata, allora viene utilizzato il parametro * <code>'title'</code> dell'applicazione come prefisso, sempre che sia stato impostato. Il separatore * tra il prefisso e il titolo della pagina può essere specificato tramite il parametro <code>'titleSeparator'</code> * dell'applicazione. Altrimenti viene utilizzato di default il carattere '-'.</li> * </ul> * Quindi imposta la descrizione della pagina secondo i seguenti criteri: * <ul> * <li>Se la proprietà <code>$pageDescription</code> non è assegnata esplicitamente viene utilizzato * il parametro <code>'description'</code> dell'applicazione.</li> * <li>Se nemmeno il parametro <code>'description'</code> è assegnato viene sollevata un'eccezione</li> * </ul> * Le impostazioni vengono fatte in questo metodo per consentire l'assegnazione del valore * alla proprietà <code>$pageTitle</code> e <code>$pageDescription</code> nella view invece che nel controller. * @throws \yii\base\InvalidConfigException Se nessun titolo o nessuna descrizione sono stati impostati */ public function afterRender($viewFile, $params, &$output) { parent::afterRender($viewFile, $params, $output); # titolo if ($this->pageTitle) { if (isset(Yii::$app->params['title'])) { $this->title = Yii::$app->params['title'] . ' ' . (isset(Yii::$app->params['titleSeparator']) ? Yii::$app->params['titleSeparator'] : '-') . ' ' . $this->pageTitle; } } else { if (isset(Yii::$app->params['title'])) { $this->title = Yii::$app->params['title']; } else { throw new \yii\base\InvalidConfigException('Il parametro \'title\' non è stato impostato.'); } } # descrizione if (!$this->pageDescription) { if (isset(Yii::$app->params['description'])) { $this->pageDescription = Yii::$app->params['description']; } else { throw new \yii\base\InvalidConfigException('Il parametro \'description\' non è stato impostato.'); } } else { } }
/** * @inheritdoc */ public function registerJs($js, $position = null, $key = null) { if ($position === null && NgView::$instance) { $position = NgView::$instance->getController() ?: self::POS_READY; } parent::registerJs($js, $position, $key); }
/** * This View class overrides render and findViewFile * to use the theme view files */ public function render($view, $params = array(), $context = null) { if ($context === null) { $context = $this->context; } return parent::render($view, $params, $context); }
/** * @inheritdoc */ public function afterRender($viewFile, $params, &$output) { parent::afterRender($viewFile, $params, $output); if (isset($params['dataProvider']) && $params['dataProvider'] instanceof DataProviderInterface && $params['dataProvider']->pagination instanceof Pagination) { $this->title .= $this->getPage($params['dataProvider']->pagination); } }
public function registerAssetFiles(View $view) { $manager = $view->getAssetManager(); $arr_js = $this->js; $arr_css = $this->css; if (isset($view->context->layout) && $view->context->layout === 'parts') { $arr_js = $this->js_parts; $arr_css = $this->css_parts; } foreach ($arr_js as $js) { $view->registerJsFile($manager->getAssetUrl($this, $js), $this->jsOptions); } foreach ($arr_css as $css) { $view->registerCssFile($manager->getAssetUrl($this, $css), $this->cssOptions); } }
/** * Generates a hashed variable to store the plugin `clientOptions`. Helps in reusing the variable for similar * options passed for other widgets on the same page. The following special data attribute will also be * setup for the input widget, that can be accessed through javascript: * * - 'data-plugin-tagsinput' will store the hashed variable storing the plugin options. * * @param View $view the view instance */ protected function hashPluginOptions($view) { $encOptions = empty($this->clientOptions) ? '{}' : Json::encode($this->clientOptions); $this->_hashVar = self::PLUGIN_NAME . '_' . hash('crc32', $encOptions); $this->options['data-plugin-' . self::PLUGIN_NAME] = $this->_hashVar; $view->registerJs("var {$this->_hashVar} = {$encOptions};\n", View::POS_HEAD); }
/** * @param \yii\web\View $view */ public static function noConflict($view) { //list(, $url) = \Yii::$app->assetManager->publish('@im/elfinder/assets'); list(, $url) = \Yii::$app->assetManager->publish('@app/modules/elfinder/src/assets'); //$view->registerJsFile($url . '/js/no.conflict.js', ['depends' => [JqueryAsset::className()]]); $view->registerCssFile($url . '/css/no.conflict.css'); }
/** * Registers this asset bundle with a view. * @param \yii\web\View $view the view to be registered with * @return static the registered asset bundle instance */ public static function register($view) { $js = <<<JS \$('[data-toggle="tooltip"]').tooltip() JS; $view->registerJs($js, View::POS_READY); return parent::register($view); }
public function beforeRender() { $url = Url::to(['/seoToolbar/toolbar/index']); $this->owner->registerJs(<<<JAVASCRIPT \$.get("{$url}", function(data) { \$('body').prepend(data); }); JAVASCRIPT , View::POS_READY); }
/** * Registers this asset bundle with a view. * @param \yii\web\View $view the view to be registered with * @return static the registered asset bundle instance */ public static function register($view) { $commentsModuleID = Comments::getInstance()->commentsModuleID; $getFormLink = Url::to(["/{$commentsModuleID}/default/get-form"]); $js = <<<JS commentsModuleID = "{$commentsModuleID}"; commentsFormLink = "{$getFormLink}"; JS; $view->registerJs($js, View::POS_HEAD); return parent::register($view); }
/** * * @param View $view * @param array $data */ public static function register($view, $data = [], $position = View::POS_BEGIN) { $default = ['config' => ['delay' => 1000, 'limit' => 20, 'checkStock' => false, 'debug' => YII_ENV == 'dev']]; $js = "\n biz = " . Json::encode(ArrayHelper::merge($default, $data)) . ";\n"; $view->registerJs($js, $position); BizAsset::register($view); }