0

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.