开发者

Using headScript() inside custom view helper

开发者 https://www.devze.com 2023-04-01 01:59 出处:网络
I have created a custom view helper and i\'m calling it successfully. Only problem that i\'m having is that it seems as though i\'m unable to inject code into the headScript by doing the following. Ev

I have created a custom view helper and i'm calling it successfully. Only problem that i'm having is that it seems as though i'm unable to inject code into the headScript by doing the following. Everything else inside my view helper is working perfectly.

$this->view->headScript()->captureStart();
echo '
    $(function开发者_如何学C() {
        //js code here              
    });
';  
$this->view->headScript()->captureEnd();

Any help would be appreciated.

Further investigation: Seems as though this is only happening on view helpers called from my layout. Calling the view helper from inside a view script works. I'm stumped!

More Investigation: echoing out the headscript like below works. anyone know why that is?

echo $this->view->headScript()->appendFile(filename) // works
echo $this->view->headScript()->appendScript(script) // works


Although it might be a little too late:

This probably happens because when you call the headScript() ViewHelper in your layout script below the head area of the HTML document it will not be echoed. If you echo out the result of the appendScript function the headScript() will return $this and thus echo out all remaining scripts. The effect is that your script-tag will not be in the head area of your HTML document. Instead it will be somewhere inside the body tag.

A solution might be to save the result of the view helper to a variable BEFORE the head area is echoed. Afterwards you could echo the content of that variable.

<?php
$myResult = $this->myViewHelper();
?><html>
    <head>
        <?php echo $this->headScript() ?>
    </head>
    <body>
        <?php echo $myResult ?>
    </body>
</html>


Have you tried to use the appendScript() method?

I mean:

$this->view->headScript()->appendScript('$(function() {//js code here });', $type = 'text/javascript');)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号