Call A Javascript-Function Within A View

Hello together,

is there a adequate function something like:


   Yii::writeJavaScript("mayBeAnExistingJavaScriptFunction($someValuefromPHP)");

   Yii::writeJavaScript("console.log($someValuefromPHP)");


   // or simple call an existing javascript function

   Yii::writeJavaScript("callThatFunctionNow()");



I would like to shorten following statement (within a view):


echo "

        <script type='text/javascript'>

           // do something 

           console.log($myPHPVariable);

        </script>

    ";



thank you very much…

I’m not sure if I’m completely understanding, but look at CClientScript::registerScript(). You can use it to insert javascript code into various parts of your completed page.

I am thinking of simple inline scripts, without registering anything…

Inside the view you can write simple scripts like this:


<script type='text/javascript'>

// do something 

console.log('<?= $myPHPVariable ?>');

</script>

Magic, huh?

ps. watch out for quotes.

I think you are not able to understand this question dear Orey :)

p.s. it is about shortening the code and to not write


<script type='text/javascript'>

..

</script>

everytime…

You could write your own wrapper function to output the tags, but it’s probably better for readability to leave them in the view. You’ll also get syntax highlighting from your editor by writing the script directly in the view.

Well, isn’t “<script></script>” already short enough?..

Seems like I’m really misunderstanding you.

I seldom write:




<script type='text/javascript'>

...

</script>



Probably never.

It’s just because I usually use CClientScript::registerScript() to write a jQuery code which should be called after the document get ready.

But if I ever have to write a simple plain inline script, I would do it like Keith and ORey. Why don’t you do it simple? :)

The answer is very simple:

I don’t want to change from php to javascript

Just like writing


  echo CHtml::button(..

instead of


  echo "<input type="button" ...

Is it really so difficult to understand? But by the way, you must not understand my intention, it is more than enough to read: "No there is not such a function". There is unfortunately plenty of OReys on this planet…

But many thanks for all the well-intentioned advices…

kind regards from Vienna…

Yes, it is.

Because in the first post you said, I quote, "within a view".

And within a view doing this


  echo "<input type="button" ...

is unnecessary, you can do just


<input type="button"

without any php, because views are made for that.

And yes, it’s hard for me to understand why use “php echo” for things than can be done in a simple way.

I’ll go and kill myself.

Don’t do this, that was a joke… ;)

I never saw a view without php…