如何在 Cake Php 中为 Html 创建自定义脚本标签

How to make a custom script tag for Html in Cake Php

我试图在 CakePHP 2.10.22 中导入一个 js 文件作为类型模块。你可以这样做

echo $this->Html->script('test', array('inline' => false, 'type' => 'module'));

但这导致标签像 <script type="text/javascript" type="module">

我也累

echo $this->Html->tag(
    'script',
    null,
    array(
        'type' => 'module',
        'src' => '/test/js/objects/test.js'
    )
);

但它并没有把它放在头部 html 标签内。

有没有办法添加或制作一个自定义助手来将其添加到头部?

使用 HTML 助手时,一种选择是自定义用于生成脚本标签的模板,即 javascriptlink,默认情况下 has the type attribute hard coded:

// in app/Config/html_tags.php
$config = array(
    'tags' => array(
        'javascriptlink' => '<script src="%s"%s></script>',
        // ...
    ),
);
// in your view layout or template
$this->Html->loadConfig('html_tags');

// or in your (App)Controller
public $helpers = array(
    'Html' => array(
        'configFile' => 'html_tags',
    ),
);

这将要求您始终为脚本标记指定 type 以备不时之需。

另一种选择是生成自定义标签,如您的问题所示,并使用视图的 append() 方法将其添加到在您的布局中呈现的相应视图块,默认情况下是块名为 script:

$scriptTag = $this->Html->tag(/* ... */);
$this->append('script', $scriptTag);

如果您愿意,这当然可以在 custom/extended HTML 助手中实现。

另见