Adding Javascript without putting the code in quotes

One issue I find a little frustrating with Yii2 is the way javascript is registered using

$this->registerJs("$('body').on('click', '#param', function($data){



Having to put javascript in quotes I lose syntax highlighting and code completion.

Does anyone know of an open source library that will allow the addition of Javascript that does require the code to go inside that function directly?

Use heredoc or nowdoc syntax (

$this->registerJs( <<< EOT_JS

$('body').on('click', '#param', function($data){





Pay attention that closure EOT_JS is at start of line.

Fabrizio Caldarelli’s solution works well if your IDE supports Javascript code completion / highlighting in PHP heredoc string literals. Otherwise use registerJs only for small snippets that doesn’t really require code completion and for longer Javascript parts there are a few alternatives:

[list=1][]Store them in a separate file.[]Use beginBlock() / endBlock().[*]Simply use <script> tags. Requires all dependencies (Jquery, etc.) to be loaded in the <head> of the page which impacts negatively on page loading time, but acceptable for applications relying heavily on Javascript / AJAX.[/list]

Easier yet:

<?php ob_start();?>
var f = "I'm a variable";
<?php $script = ob_get_clean(); ?>
<?php $this->registerJs($script); ?>

This way you keep your syntax highlighting.

1 Like