如何将换行符添加到CakePHP脚本块

How do I add newlines to a CakePHP script block?

本文关键字:CakePHP 脚本 添加 换行符      更新时间:2023-09-26

使用CakePHP,可以通过在视图中放入以下内容来插入普通JavaScript:

$this->Html->scriptStart(array('inline' => false));
echo 'alert("Hello world!");';
$this->Html->scriptEnd();

不幸的是,如果您有多个echo语句,那么所有的文本将被压缩到一个长行中。是否有办法分割行并插入换行符?

我已经试过在echo'd语句的末尾加上'n,但是没有效果。

我认为正确使用分号可以使JS在一行中正确运行,但这会带来痛苦的阅读和调试体验。

如果你不需要,你可以试着不把它放在PHP中:

<?php $this->Html->scriptStart(array('inline' => false)); ?>
     alert("Hello world!");
     alert("Hello world!");
<?php $this->Html->scriptEnd(); ?>

然后使用正常的js格式。

或者,您可以使用PHP_EOL回显不在字符串字面值内的换行符。

<?php
     $this->Html->scriptStart(array('inline' => false));
     echo 'alert("Hello world!");' . PHP_EOL;
     echo 'alert("Hello world!");';
     $this->Html->scriptEnd();
?>

我不确定我是否正确理解你的问题,但尽量逃避你的'n,因为php会在javascript轮流之前将其解释为正常字符串,因此例如:

$first = "This is first line''n";
$both  = $first . "This is second line";   

我最终通过使用Js->缓冲区解决了这个问题,如下所示:

echo $this->Js->buffer('$(''<input type="button" id="instaSave" value="Save"/>'')
    .click(function(){ 
        $(this).val("Saving...");
        $(this).parents("form:first").ajaxSubmit({
            success: function(responseText, responseCode) {
                $(".food").each(function(fIndex){
                   ...
');