I
I
Ivan Trofimov2014-02-11 06:14:43
JavaScript
Ivan Trofimov, 2014-02-11 06:14:43

How to pass parameters to JS in Yii or write a piece of js code to a controller/component property?

Hello. The situation is as follows:
In the Controller, I created 2 array() parameters: $cssArr and $jsArr. I pass the styles and scripts used on this page to them from the view, and then in the layout using foreach($this->cssArr as style) they are loaded (styles in the layout header, and scripts before the closing one to speed up the page load time). But ran into a problem. I wrote a jQuery plugin, in which, during initialization, it is necessary to pass parameters:
1. unixtime of the beginning of the current day and
2. unixtime of the next day.
Moreover, I ask the server for unixtime, not the client, and only then transfer it to JS. But there was a difficulty with the initialization of this plugin. In the layout, I can't initialize it because the jQuery library is not yet connected (it is connected at the end of the page).
I think we can create a new property (public $jsCode) in the Component and pass the necessary JS code into it from our view, and display the value of this property in the layout after jQuery initialization. But I don’t know how to correctly write this code into a variable so as not to code and escape all the quotes of my JS? Perhaps ob_stat will save, are there any ready-made solutions in Yii? I looked through the documentation and couldn't find anything.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2014-02-11
@AMar4enko

Poor search, CClientScript is used for this.
In fact, your story with $cssArr and $jsArr is a cycle, because CClientScript provides all the tools necessary for this.
For example, to add a JS file to the output page, use
www.yiiframework.com/doc/api/1.1/CClientScript#reg...
To add a CSS file,
www.yiiframework.com/doc/api/1.1/CClientScript#reg. ..
And for adding a "raw" script
www.yiiframework.com/doc/api/1.1/CClientScript#reg...
In all of the above methods, you can choose where exactly Yii will push these files and scripts. Specifically for raw scripts, there is CClientScript::POS_READY - i.e. the passed code will be in jQuery ready wrapper and will be executed after jQuery is initialized

N
nikel303, 2014-02-14
@nikel303

I did it this way:
In the controller base class:

class Controller extends CController {
    public $jsParams = array();
    /* ... */

further, in a view or in an action , we
add elements to this array, for example:
public function actionIndex() {
  $oRequest = Yii::app()->getRequest();
  $this->jsParams['csrf'] = array($oRequest->csrfTokenName => $oRequest->getCsrfToken());
}

well, then we render this array in the main layout, for example:
in scripts can be accessed like this:
jsParams = jsParams || {};
console.log(jsParams);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question