headScript()->appendFile 与视图中的 headScript()->prependFile 具有相

headScript()->appendFile has the same behaviour as headScript()->prependFile from view

本文关键字:headScript prependFile appendFile 视图      更新时间:2023-09-26

我遇到了一些问题。 appendFile 似乎在视图中不起作用。如果我将其更改为 prependFile,它具有相同的行为。

布局.phtml

<!doctype html>
<html lang="en" dir="ltr">
    <head>
        <?php
        $this->headScript()->appendFile('http://code.jquery.com/ui/1.10.3/jquery-ui.js'); 
        $this->headScript()->appendFile('/theme/javascripts/application.js'); 
        $this->headScript()->appendFile('/js/own.js'); 
        ?>
    </head>
    <body>
        <?php echo $this->layout()->content; ?>
        <?php echo $this->headScript() ?> 
    </body>
</html>

索引.phtml

<?php $this->headScript()->appendFile('/js/another.js') ?>

输出

<!doctype html>
<html lang="en" dir="ltr">
<head>
</head>
<body>      
    <script type="text/javascript" src="/js/another.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript" src="/theme/javascripts/application.js"></script>
    <script type="text/javascript" src="/js/own.js"></script> 
</body>
</html>

如您所见/js/other.js将是第一个js。这不是我想要的,我想把它放在最后。有人知道出了什么问题吗?

/js/another.js

开头,因为首先调用layout.phtml,然后在调用<?php echo $this->layout()->content; ?>时调用index.phtml文件。

现在在你的代码中,你已经:
<?php echo $this->layout()->content; ?> <?php echo $this->headScript() ?>

所以它实际上是在调用layout(),因此调用index.phtml,然后调用拥有其余部分的headscript()。它附加index.phtml中提到的js,然后附加headscript()的其余部分。反过来试试...

您应该尝试:

<!doctype html>
<html lang="en" dir="ltr">
    <head>
        <?php
            $this->headScript()->appendFile('http://code.jquery.com/ui/1.10.3/jquery-ui.js'); 
            $this->headScript()->appendFile('/theme/javascripts/application.js'); 
            $this->headScript()->appendFile('/js/own.js'); 
        ?>
    </head>
    <body>
        <?php echo $this->headScript() ?> 
        <?php echo $this->layout()->content; ?>
    </body>
</html>

理想情况下,您应该在<HEAD>部分中输出所有脚本。

视图脚本在布局之前呈现,因此当您追加/js/another.js时,没有其他脚本,这就是为什么布局稍后添加的脚本最终会在其之后。

您应该能够通过将布局中的所有appendFile()调用更改为prependFile()来实现所需的顺序。(而且您可能需要颠倒它们的顺序,因为您现在处于前置状态。然后,执行顺序应为:

  • 视图脚本追加/js/another.js
  • 布局前置/js/own.js
  • 布局前置/theme/javascripts/application.js
  • 布局前置http://code.jquery.com/ui/1.10.3/jquery-ui.js

此外,您可能需要考虑为此使用内联脚本帮助程序(其工作方式相同(,因为将头脚本输出脚本<body>可能会使未来处理代码的开发人员感到困惑。