Registers a JS code block.
public registerJs ( string $js, integer $position = self::POS_READY, string $key = null ) | ||
$js | string | the JS code block to be registered |
$position | integer | the position at which the JS script tag should be inserted in a page. The possible values are: - [[POS_HEAD]]: in the head section - [[POS_BEGIN]]: at the beginning of the body section - [[POS_END]]: at the end of the body section - [[POS_LOAD]]: enclosed within jQuery(window).load(). Note that by using this position, the method will automatically register the jQuery js file. - [[POS_READY]]: enclosed within jQuery(document).ready(). This is the default value. Note that by using this position, the method will automatically register the jQuery js file. |
$key | string | the key that identifies the JS code block. If null, it will use $js as the key. If two JS code blocks are registered with the same key, the latter will overwrite the former. |
/** * * @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); }
/** * 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; }
/** * @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'); } }
/** * 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); }
/** * Registers the CSS and JS files with the given view. * @param View $view the view that the asset files are to be registered with. */ public function registerAssetFiles($view) { if ($this->page_loading) { $view->registerJs('NProgress.start();', View::POS_BEGIN); $view->registerJs('NProgress.done();', View::POS_LOAD); $this->jsOptions['position'] = View::POS_HEAD; } if ($this->configuration !== null) { $view->registerJs('NProgress.configure(' . Json::encode($this->configuration) . ');', $this->jsOptions['position']); } if ($this->pjax_events) { $jsPjax = <<<PJAX jQuery(document).on('pjax:start', function() { NProgress.start(); }); jQuery(document).on('pjax:end', function() { NProgress.done(); }); PJAX; $view->registerJs($jsPjax, View::POS_END); $this->depends[] = 'yii\\widgets\\PjaxAsset'; } if ($this->jquery_ajax_events) { $jsAjax = <<<AJAX jQuery(document).on('ajaxStart', function() { NProgress.start(); }); jQuery(document).on('ajaxComplete', function() { NProgress.done(); }); AJAX; $view->registerJs($jsAjax, View::POS_END); $this->depends[] = 'yii\\widgets\\JqueryAsset'; } parent::registerAssetFiles($view); }
/** * @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); }
/** * @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); }
/** * 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); } }
public function registerJs($js, $position = self::POS_READY, $key = null) { Yii::log('Registering ' . $js, 'info', __METHOD__); // Register in parent in order to trigger any errors with the parameters parent::registerJs($js, $position, $key); // Register using Yii1 client script $clientScript = Yii::app()->getClientScript(); $clientScript->registerScript(uniqid(), $js, $position); }
/** * 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); }
/** * @inheritdoc */ public function registerJs($js, $position = null, $key = null) { if ($position === null) { if (Angular::$instance && Angular::$instance->controller) { $position = Angular::$instance->controller; } else { $position = self::POS_READY; } } parent::registerJs($js, $position, $key); }
/** * 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); } }
/** * Registers the CSS and JS files with the given view. * public $css = [ * 'css/bootstrap.min.css', * 'css/font-awesome.min.css' => array('position' => View::POS_END, 'condition' => 'lte IE 8') * ] * @param \yii\web\View $view the view that the asset files are to be registered with. */ public function registerAssetFiles($view) { foreach ($this->js as $value) { if (is_array($value)) { if (isset($value['file'])) { $js = $value['file']; unset($value['file']); $options = ArrayHelper::merge($this->jsOptions, $value); } else { if (isset($value['content'])) { $position = isset($value['position']) ? $value['position'] : $view::POS_READY; $view->registerJs($value['content'], $position); } continue; } } else { $js = $value; $options = $this->jsOptions; } if ($js[0] !== '/' && $js[0] !== '.' && strpos($js, '://') === false) { $view->registerJsFile($this->baseUrl . '/' . $js, [], $options); } else { $view->registerJsFile($js, [], $options); } } foreach ($this->css as $value) { if (is_array($value)) { if (isset($value['file'])) { $css = $value['file']; unset($value['file']); $options = ArrayHelper::merge($this->cssOptions, $value); } else { if (isset($value['content'])) { $position = isset($value['position']) ? $value['position'] : $view::POS_READY; $view->registerCss($value['content'], $position); } continue; } } else { $css = $value; $options = $this->cssOptions; } if ($css[0] !== '/' && $css[0] !== '.' && strpos($css, '://') === false) { $view->registerCssFile($this->baseUrl . '/' . $css, [], $options); } else { $view->registerCssFile($css, [], $options); } } }
/** * @param string $language * @param View $view */ public function registerLanguage($language, $view) { $sourcePath = Yii::getAlias($this->sourcePath); $fallbackLanguage = substr($language, 0, 2); $desiredFile = $sourcePath . DIRECTORY_SEPARATOR . "{$language}.js"; if (!is_file($desiredFile)) { if ($fallbackLanguage === 'en') { // en is default, there is not separate locale file for it return; } $desiredFile = $sourcePath . DIRECTORY_SEPARATOR . "{$fallbackLanguage}.js"; if (file_exists($desiredFile)) { $language = $fallbackLanguage; } } $view->registerJsFile($this->baseUrl . "/{$language}.js"); $js = "moment.locale('{$language}')"; $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) { $view->registerJs(<<<JS yii.allowAction = function (e) { var message = e.data('confirm'); return message === undefined || yii.confirm(message, e); }; yii.confirm = function (message, ok, cancel) { bootbox.confirm( { message: message, buttons: { confirm: {label: window.i18n['yes'] || 'Yes' }, cancel: {label: window.i18n['cancel'] || 'Cancel' } }, callback: function (confirmed) { if (confirmed) { !ok || ok(); } else { !cancel || cancel(); } } } ); return false; }; window.alert = function (message) { bootbox.alert({ message: message }); return false; }; JS ); parent::registerAssetFiles($view); }
/** * Registers this asset bundle with a view. * @param \yii\web\View $view * @return static the registered asset bundle instance */ public static function register($view) { $messages = ['condMsgError' => \Yii::t('analytics', 'Condition is already added'), 'aggrMsgError' => \Yii::t('analytics', 'Aggregation is already added')]; $view->registerJs('var errMessages = ' . \yii\helpers\Json::encode($messages) . ';' . PHP_EOL, \yii\web\View::POS_HEAD); return parent::register($view); }
/** * Registers timeago javascript. * * @param \yii\web\View $view * @param array $settings */ public function registerJs($view, $settings = []) { if ($this->settings || $settings) { $settings = Json::htmlEncode(array_merge($this->settings, $settings)); $view->registerJs("jQuery.extend(jQuery.timeago.settings, {$settings});", $view::POS_READY, 'timeagoOptions'); } $view->registerJs("jQuery('time.timeago').timeago();", $view::POS_READY, 'timeago'); }
/** * @param View $view */ public function renderJS(View $view) { $jsString = "\n BrightNestableList.NestableListOptions = {\n listNodeName : '{$this->listNodeName}',\n itemNodeName : '{$this->itemNodeName}',\n rootClass : '{$this->rootClass}',\n listClass : '{$this->listClass}',\n itemClass : '{$this->itemClass}',\n dragClass : '{$this->dragClass}',\n handleClass : '{$this->handleClass}',\n collapsedClass : '{$this->collapsedClass}',\n placeClass : '{$this->placeClass}',\n noDragClass : '{$this->noDragClass}',\n emptyClass : '{$this->emptyClass}',\n expandBtnHTML : '{$this->expandBtnHTML}',\n collapseBtnHTML : '{$this->collapseBtnHTML}',\n group : '{$this->group}',\n maxDepth : '{$this->maxDepth}',\n threshold : '{$this->threshold}'\n };\n BrightNestableList.initNestableList();\n "; if ($this->collapseAll) { $jsString .= "\$('.dd').nestable('collapseAll')"; } return $view->registerJs($jsString); }
/** * * @param View $view */ public function register($view) { $js = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\r\n\t\t\t\t\t\t(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\r\n\t\t\t\t\t\tm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\r\n\t\t\t\t\t})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n"; if ($this->useUserId && !Yii::$app->user->isGuest) { $this->defaultTrackingOpts['userId'] = 'gauid_' . Yii::$app->user->id; } $opts = $this->defaultTrackingOpts ? ', ' . Json::encode($this->defaultTrackingOpts) : ''; $js .= "ga('create', '{$this->defaultTrackingId}', 'auto'{$opts});"; if ($this->_plugins) { $js .= implode("\n", $this->_plugins); } if ($this->_sets) { $js .= "ga('set', " . Json::encode($this->_sets) . ");"; } if ($this->_sends) { $js .= implode("\n", $this->_sends); } $view->registerJs($js, View::POS_HEAD, 'ga'); }
/** * Infinity notify loop for Demo * * @param \yii\web\View $view */ public static function demo($view) { $id = self::$_id; $randomArray = json_encode([self::CLASS_ERROR, self::CLASS_INFO, self::CLASS_SUCCESS, self::CLASS_WARNING]); $view->registerJs("setInterval(function(){\n\t\t\tvar timeCookie = new Date();\n\t\t\ttimeCookie = timeCookie.toString();\n\t\t\tvar randomArray = {$randomArray};\n\t\t\tvar item = randomArray[Math.floor(Math.random()*randomArray.length)];\n\t\t\tvar tempalate = new Array(65).join('*') + 'a:2:{i:0;s:" . strlen($id) . ":\"{$id}\";i:1;a:1:{i:0;a:2:{s:5:\"class\";s:' + item.length + ':\"' + item + '\";s:7:\"message\";s:' + timeCookie.length + ':\"' + timeCookie + '\";}}}';\n\t\t\t\$.cookie('{$id}',tempalate);\n\t\t\t\$.ajax({url:window.location});\n\t\t},5000);"); }
echo Html::csrfMetaTags(); ?> <title><?php echo Html::encode($this->title); ?> </title> <link rel="shortcut icon" href="<?php echo $this->theme->getUrl('images/komponen/favicon.ico'); ?> " type="image/x-icon" /> <?php $this->head(); ?> <?php \yii\web\View::registerJs('var base_url = ' . json_encode(yii\helpers\Url::base(true)) . '', yii\web\View::POS_HEAD); ?> <!-- Facebook Pixel Code --> <!-- End Facebook Pixel Code --> <!-- Google Analytics --> </head> <body> <?php $this->beginBody(); ?>
/** * @inheritdoc */ public function registerJs($js, $position = self::POS_READY, $key = null) { $this->viewElementsGathener->gather(__FUNCTION__, func_get_args()); return parent::registerJs($js, $position, $key); }
public function beforeRender() { $url = Url::to(['/seoToolbar/toolbar/index']); $this->owner->registerJs(<<<JAVASCRIPT \$.get("{$url}", function(data) { \$('body').prepend(data); }); JAVASCRIPT , View::POS_READY); }
/** * 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); }
/** * 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); }
/** * 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); }