Yii2 js php переменная

Working with Client Scripts ¶

Modern web applications, additionally to static HTML pages that are rendered and sent to the browser, contain JavaScript that is used to modify the page in the browser by manipulating existing elements or loading new content via AJAX. This section describes methods provided by Yii for adding JavaScript and CSS to a website as well as dynamically adjusting these.

Registering scripts ¶

When working with the yii\web\View object you can dynamically register frontend scripts. There are two dedicated methods for this:

Registering inline scripts ¶

Inline scripts are useful for configuration, dynamically generated code and small snippets created by reusable frontend code contained in widgets. The registerJs() method for adding these can be used as follows:

$this->registerJs( "$('#myButton').on('click', function() < alert('Button clicked!'); >);", View::POS_READY, 'my-button-handler' ); 

The first argument is the actual JS code we want to insert into the page. It will be wrapped into a tag. The second argument determines at which position the script should be inserted into the page. Possible values are:

  • View::POS_HEAD for head section.
  • View::POS_BEGIN for right after opening .
  • View::POS_END for right before closing .
  • View::POS_READY for executing code on the document ready event. This will automatically register jQuery and wrap the code into the appropriate jQuery code. This is the default position.
  • View::POS_LOAD for executing code on the document load event. Same as the above, this will also register jQuery automatically.

The last argument is a unique script ID that is used to identify the script code block and replace an existing one with the same ID instead of adding a new one. If you don’t provide it, the JS code itself will be used as the ID. It is used to avoid registration of the same code multiple times.

Registering script files ¶

The arguments for registerJsFile() are similar to those for registerCssFile(). In the following example, we register the main.js file with the dependency on the yii\web\JqueryAsset. It means that the main.js file will be added AFTER jquery.js . Without such dependency specification, the relative order between main.js and jquery.js would be undefined and the code would not work.

An external script can be added like the following:

$this->registerJsFile( '@web/js/main.js', ['depends' => [\yii\web\JqueryAsset::class]] ); 

This will add a tag for the /js/main.js script located under the application base URL.

It is highly recommended to use asset bundles to register external JS files rather than registerJsFile() because these allow better flexibility and more granular dependency configuration. Also using asset bundles allows you to combine and compress multiple JS files, which is desirable for high traffic websites.

Registering CSS ¶

Similar to JavaScript, you can register CSS using registerCss() or registerCssFile(). The former registers a block of CSS code while the latter registers an external CSS file.

Registering inline CSS ¶

The code above will result in adding the following to the section of the page:

style> body < background: #f00; > style> 

If you want to specify additional properties of the style tag, pass an array of name-values to the second argument. The last argument is a unique ID that is used to identify the style block and make sure it is only added once in case the same style is registered from different places in the code.

Registering CSS files ¶

A CSS file can be registered using the following:

$this->registerCssFile("@web/css/themes/black-and-white.css", [ 'depends' => [\yii\bootstrap\BootstrapAsset::class], 'media' => 'print', ], 'css-print-theme'); 

The above code will add a link to the /css/themes/black-and-white.css CSS file to the section of the page.

  • The first argument specifies the CSS file to be registered. The @web in this example is an alias for the applications base URL.
  • The second argument specifies the HTML attributes for the resulting tag. The option depends is specially handled. It specifies which asset bundles this CSS file depends on. In this case, the dependent asset bundle is yii\bootstrap\BootstrapAsset . This means the CSS file will be added after the CSS files from yii\bootstrap\BootstrapAsset .
  • The last argument specifies an ID identifying this CSS file. If it is not provided, the URL of the CSS file will be used instead.

It is highly recommended to use asset bundles to register external CSS files rather than registerCssFile(). Using asset bundles allows you to combine and compress multiple CSS files, which is desirable for high traffic websites. It also provides more flexibility as all asset dependencies of your application are configured in one place.

Registering asset bundles ¶

As was mentioned earlier it’s recommended to use asset bundles instead of registering CSS and JavaScript files directly. You can get details on how to define asset bundles in the «Assets» section. As for using already defined asset bundles, it’s very straightforward:

\frontend\assets\AppAsset::register($this); 

In the above code, in the context of a view file, the AppAsset bundle is registered on the current view (represented by $this ). When registering asset bundles from within a widget, you would pass the $view of the widget instead ( $this->view ).

Generating Dynamic Javascript ¶

In view files often the HTML code is not written out directly but generated by some PHP code dependent on the variables of the view. In order for the generated HTML to be manipulated with Javascript, the JS code has to contain dynamic parts too, for example the IDs of the jQuery selectors.

To insert PHP variables into JS code, their values have to be escaped properly. Especially when the JS code is inserted into HTML instead of residing in a dedicated JS file. Yii provides the htmlEncode() method of the Json helper for this purpose. Its usage will be shown in the following examples.

Registering a global JavaScript configuration ¶

In this example we use an array to pass global configuration parameters from the PHP part of the application to the JS frontend code.

$options = [ 'appName' => Yii::$app->name, 'baseUrl' => Yii::$app->request->baseUrl, 'language' => Yii::$app->language, // . ]; $this->registerJs( "var yiiOptions hljs-string">";", View::POS_HEAD, 'yiiOptions' ); 

The above code will register a -tag containing the JavaScript variable definition, e.g.:

var yiiOptions = "appName":"My Yii Application","baseUrl":"/basic/web","language":"en">; 

In your JavaScript code you can now access these like yiiOptions.baseUrl or yiiOptions.language .

Passing translated messages ¶

You may encounter a case where your JavaScript needs to print a message reacting to some event. In an application that works with multiple languages this string has to be translated to the current application language. One way to achieve this is to use the message translation feature provided by Yii and passing the result to the JavaScript code.

$message = \yii\helpers\Json::htmlEncode( \Yii::t('app', 'Button clicked!') ); $this->registerJs($message ); >); JS ); 

The above example code uses PHP Heredoc syntax for better readability. This also enables better syntax highlighting in most IDEs so it is the preferred way of writing inline JavaScript, especially useful for code that is longer than a single line. The variable $message is created in PHP and thanks to Json::htmlEncode it contains the string in valid JS syntax, which can be inserted into the JavaScript code to place the dynamic string in the function call to alert() .

Note: When using Heredoc, be careful with variable naming in JS code as variables beginning with $ may be interpreted as PHP variables which will be replaced by their content. The jQuery function in form of $( or $. is not interpreted as a PHP variable and can safely be used.

The yii.js script ¶

  • Yii JavaScript Modules
  • CSRF param handling
  • data-confirm handler
  • data-method handler
  • script filtering
  • redirect handling

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing variables from php to js #305

passing variables from php to js #305

Comments

How about giving View the possibility to pass variables from your backend code to the client side portion of it? From an API point of view, it should be similar to passing variables from Controller to the rendered view:

// passing $model from controller to view public function actionLogin() < $model = new LoginForm(); echo $this->render('login', array( 'model' => $model, )); > // inside the view, pass $name to js /** * @var yii\base\View $this */ $this->registerJsFile($url,array( 'ns' => 'app.login', // maybe provide an optional namespace 'vars' => array( 'name' => $model->name ), ));

Maybe registerJsFile’s options array is not the right place to define the variables, but you get the idea.

Implementation could be something like:

public function registerJsVar($ns, $key, $val) < $this->registerJs("$ns.$key=".json_encode($val)); >

The text was updated successfully, but these errors were encountered:

Basically, I hope it encourages people to put JS code in *.js files, that is parameterized to work with some variables they provide, instead of registering (possibly growing, hard to maintain) snippets of JS, which they generate somewhere in their PHP files.

I am still not convinced. I don’t think having this method would encourage people to do as you described. This method will actually introduce some problems. For example, $ns is not defined (possibly because the js file defining it is not included.)

I think the namespacing problem can be solved (not sure if it is necessary to let the user customize it though). Basically, they need to be collected and rendered when the script rendering happens with standard ns = ns || <>; ns.sub_ns = ns.sub_ns || <>; technique.

By the way: will yii introduce a JS namespace for itself?

Of course, I’m willing to prepare a proper PR for the feature (but can only do it in a few weeks, not right now). I think it’s quite a common task to feed JS code with some values you have in PHP variables, so I personally think it would be nice to have it, especially if it fits into the framework and feels similar to passing variables when rendering views.

Passing PHP variables to js is very trivial: just a plain json_encode will do. I can’t see much value of providing a PHP method to do that.

Yes, yii2 does introduce a js namespace, as you can see in yii/assets/yii.js .

As trivial as it is, this took me a long time to figure out. So just to be clear:

$this->registerJs(«var Yii = «. json_encode($config).»;»,View::POS_HEAD);

If you place this in your layouts/main.php file Yii.token will be available globally in your js

I know that it is probably a bit late, but I think that a shortcut method to register vars is quite useful. With better support of combining all vars in the same place of the document.

Shortcut example:
$this->regJsVar(‘myAwesomeJsVar’, $myDataArray);

And all stuff of wrapping it up will be inside of the method. It’s more like a shortcut, not an enhancement.

Registering js vars through php could have a lot of benefits including debugging and improving development process. I don’t think that such a simple method could reduce productivity of the code
IMHO.

We will not include this method in core. You can create this shortcut locally in your project.

Nowadays it’s much better to render options you need in data-something HTML attributes and then access them via static JavaScript. I agree that it should not be part of the core framework. If required it could be achieved easily as @samuelbirk explained.

Источник

Читайте также:  Сумму цифр целого числа java
Оцените статью