3

I need <script> in header to define a JavaScript variable (var dates={...};) which is to be used from a .js script.

It should be preferably in header and not inside jQuery(function($){...}) not to hide the variable from using it by my .js script.

Can it be done in any other way than modifying the layout?

4
  • 4
    How about Yii::app()->clientScript->registerScript($script_source, CClientScript::POS_HEAD) in the controller? Commented Jun 2, 2013 at 17:48
  • @DCoder: Your code produces a script wrapped into jQuery(function($){...}) what is unsatisfactory for me. Commented Jun 2, 2013 at 18:07
  • You can still export a symbol into the global scope... $(function() { window.dates = ... ; }) (though you might want to think about a more unique name for it). Commented Jun 2, 2013 at 18:10
  • 8
    @DCoder's example is wrong in that it's missing the first argument (script id). The correct example is Yii::app()->clientScript->registerScript($scriptId, $scriptSource, CClientScript::POS_HEAD) and for me at least, on Yii 1.1.13, it will not be wrapped inside jQuery(). That would happen on CClientScript::POS_READY. Commented Jun 3, 2013 at 7:27

1 Answer 1

2

I usually do this:

Yii::app()->clientScript->registerScript('my vars','
    var myFirstVar="something";
    var myUrl="' . CController::createUrl("controller/action") . '";
    ,CClientScript::POS_HEAD);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.