0

I am developing a custom helper and i want that whenever i use this helper, it should load related css/js files in the header section of that particular view..

For example, if i am using "XyzHelper" in "abc" view, XyzHelper should load css/js files in header section of abc view and so on.

Here is my helper code:-

App::uses('AppHelper', 'View/Helper');
class XyzHelper extends AppHelper {
    public function show() {
        $html = new HtmlHelper(new View());
        echo $html->css('custom',array('inline'=>true));
        echo $html->script('custom.min',array('inline'=>true));                
        return "<div style='background-color:rgb(200,0,0);padding:20px;color:white;'>Hello World</div>";
    }
}

Above code is loading css/js files but not in the header section of any view.

I have tried append('css') method inside my helper but that also not seems to be working. It says 'append' does not exist.

$this->append('css','<link_to_css_file>');
Sumit Parakh
  • 1,098
  • 9
  • 19
  • You should be loading the `HtmlHelper` inside your helper using `public $helpers = array('Html');`. You can then use it like `$this->Html->css('custom',array('inline'=>true));` inside your helper methods. Also, your helper functions shouldn't be echoing out content, only returning! – drmonkeyninja May 26 '17 at 11:53

2 Answers2

0

Try changing option inline to false. As is stated in docs:

If key ‘inline’ is set to false in $options parameter, the link tags are added to the css block which you can print inside the head tag of the document.

Szymon
  • 1,385
  • 1
  • 8
  • 10
0

You could Do it using the Helper Callback:

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

class XyzHelper extends AppHelper {

    public $helpers = array('Html');

    public function beforeRenderFile($viewFile)
    {
        echo $this->Html->css('custom', array('inline'=>true));
        echo $this->Html->script('custom.min', array('inline'=>true));                
        echo "<div style='background-color:rgb(200,0,0);padding:20px;color:white;'>Hello World</div>";
    } 
}

See also

Rayann Nayran
  • 1,135
  • 7
  • 15