gpt4 book ai didi

php - CakePHP 如何从元素内部添加脚本()?

转载 作者:可可西里 更新时间:2023-11-01 00:17:13 26 4
gpt4 key购买 nike

我在 CakePHP 中有一个导航菜单 element文件 (views/elements/nav_default.ctp)。

该文件包含在另一个元素中,即标题 (views/elements/header_default.ctp),然后包含在布局文件 (views/layouts/default.ctp) 中。

我试图告诉 Cake 从 nav 元素中加载一个 js 文件 (webroot/js/mega_drop.js),如下所示:

<?php
$this->addScript('mega_drop');
?>

它不包括在内。我查看了 addScript 的文档这只是说:

Adds content to the internal scripts buffer. This buffer is made available in the layout as $scripts_for_layout. This method is helpful when creating helpers that need to add javascript or css directly to the layout. Keep in mind that scripts added from the layout, or elements in the layout will not be added to $scripts_for_layout. This method is most often used from inside helpers, like the Javascript and Html Helpers.

关键部分:

Keep in mind that scripts added from the layout, or elements in the layout will not be added to $scripts_for_layout.

那我该怎么做呢?

我想我可以添加 <script src="/js/mega_drop.js"></script>default.ctp布局。这感觉不对,因为它会将布局和元素紧密地结合在一起。

执行此操作的 CakePHP 最佳实践方法是什么?

最佳答案

addScript() 不加载文件;它将实际代码添加到 $scripts_for_layout 变量。这个想法是布局是加载 JavaScript 文件和代码的一个很好的、常见的地方。这样你就可以在一个位置输出所有代码——在头部 block 或末尾——无论哪种方式都在一起。因此,如果您处于 View 中有 JavaScript 代码的情况,而不是内联输出它,您可以将它传递给布局。

加载脚本文件的最佳方式是使用 HTML Helper- echo $this->Html->script("script or array('of', 'scripts')");考虑到这一点,您可以在元素中 $this->set('scripts', 'mega_drop'); 然后使用布局中的 $scripts 变量调用 Html Helper。

问题是:如果你的 nav_default.ctp 是从布局中调用的,它就不会工作。 $this->set() 在 View 内部工作(或从 View ),因为 View 在布局之前呈现。如果您从布局中调用您的元素,那么设置 viewVars 以在布局中使用为时已晚。 最好的办法是设置() Controller 中的脚本变量并使用 if(isset($scripts)) { echo $this->Html->script($scripts) ; 在布局中。

关于php - CakePHP 如何从元素内部添加脚本()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4717080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com