CakePHP multiple scriptBlock JavaScript code must come in one single HTML <script> Tag

190 Views Asked by At

I have multiple scriptBlock in my code which is coming from different pages, but it should create one single <script> tag for all JavaScripts written in CakePHP scriptBlock.

My below example code is creating separate <script> Tags for each.

echo $this->Html->scriptBlock(
    'jQuery(".investment-table tbody>tr").show()',
    ['block' => true]
);

echo $this->Html->scriptBlock(
    'jQuery(".investment-table tbody>tr").hide()',
    ['block' => true]
);

echo $this->Html->scriptBlock(
    'jQuery(".investment-table tbody>tr").remove()',
    ['block' => true]
);

Please suggest a proper method to achieve this from many pages.

1

There are 1 best solutions below

0
ndm On

HtmlHelper::scriptBlock() is by default ment to create a single <script> element for each call.

It shouldn't really be a problem though, as:

<script>jQuery(".investment-table tbody>tr").show()</script>
<script>jQuery(".investment-table tbody>tr").hide()</script>
<script>jQuery(".investment-table tbody>tr").remove()</script>

and

<script>
jQuery(".investment-table tbody>tr").show()
jQuery(".investment-table tbody>tr").hide()
jQuery(".investment-table tbody>tr").remove()
</script>

are functionally identical.

However, for the sake of the argument, if you for whatever reason needed things to into the same element, you could for example write to a custom block, and then output that custom block in a script block, something along the lines of this:

$this->append(
    'mergedScripts',
    'jQuery(".investment-table tbody>tr").show();'
);
$this->append(
    'mergedScripts',
    'jQuery(".investment-table tbody>tr").remove();'
);
$this->append(
    'mergedScripts',
    'jQuery(".investment-table tbody>tr").remove();'
);
echo $this->Html->scriptBlock($this->fetch('mergedScripts'));

See also