2

I am talking about the CakePHP Helper. I want to load the JS files using the helper of CakePHP.

Consider that the construction of the Helper class will load all necessary JS files.

But, I need to call that Helper in a single view multiple times. So, it's possible that the JS files will be called multiple times. I want to load those JS files only once.

Can anyone help me to cover this?

This will be my Helper script

<?php
App::uses('AppHelper', 'View/Helper');

/**
 * @alias Mathjax Class for helper
 * @description This class is to define helper in cakephp.
 */
class MathjaxHelper extends AppHelper {

    /*
     * Constructor of the class.
     */
    function __construct(View $View, $settings = array()) {
        parent::__construct($View, $settings);
        //login to load all necessary JS files.
    }

    function create() {
        //this function will return the helper html
    }

}
0

1 Answer 1

4

Use HtmlHelper::script

If you use HtmlHelper::script method, with 'inline' => false, to load the js files they will by default be included once.

Layout file

To use this method, ensure that in the layout file the $scripts_for_layout variable is echoed out. E.g.:

<html>
    <head>
        ...
    </head>
    <body>
        ...

        <?php echo $scripts_for_layout ?>
    </body> 
</html>

View files

In your views, elements or helpers - simply ensure the script method is called using the inline parameter:

<?php $this->Html->script('my', array('inline' => false)); ?>

In this way it doesn't matter how often you call the script method with a given js file - it will appear in the resultant html output only once.

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

2 Comments

You can also use $options['once'] as per documentation
True, but that's only relevant if js scripts are dumped inline in a view file (which - shouldn't be the case and isn't something I encourage).

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.