Hello,
I use netbeans as my primary IDE and I wanted to create a component for render some javascript that needs to get some parameters for php.
Before I had this js code inside a controller’s view in plain js. Now instead of put it into a .js file and register it using registerScriptFile I wanted to have it as a view and then pass php variables to it using the render function of my component.
So I’ve got the js code from the view setting the return parameter of the render method to true, and then added it to my page usin registerScript.
The only problem was that I was not able to set syntax highlight in netbeans for the view so the js code was not highlighted … (and also indentation didn’t worked)
cause when you use the registerScript method you have to omit the “<script>” tag and so netbeans isn’t happy
my solution (don’t be if it is the best one or either a wise one) the solution was to make another class / component:
<?php
class JsWidget extends CWidget {
public function parseJs($js) {
$js =preg_replace('/<!--\\[rem\\]-->.*?<!--\\[\\/rem\\]-->/is', '', $js);
return $js;
}
public function render($view, $data=null, $return=false) {
$js =parent::render($view, $data, true);
$js =$this->parseJs($js);
if ($return) {
return $js;
}
else {
echo $js;
}
}
}
?>
so that then you can just call it from the component in this way:
<?php
class MyComponent extends JsWidget {
public function run() {
$script =$this->render('MyComponent_js',array('test'=>"hello world"), true);
Yii::app()->clientScript->registerScript('test', $script, CClientScript::POS_HEAD);
}
}
?>
and write the component’s view this way:
<!--[rem]--><script type="text/javascript"><!--[/rem]-->
alert('<?=$test;?>');
<!--[rem]--></script><!--[/rem]-->
let me know what you think
bye,
Giovanni.