0

I have just started a project with cakePHP 2.0. I am using an element to render a sidebar menu. I would like to specify the css and JS files for the menu in the menu element and not add them in my head tag (in case I'd like to conditionally render different sidebars). For some reason my scripts and CSS are not being output.. any ideas why?

Layouts/Default.ctp

<head>
<?php
echo $this->fetch('css');
echo $this->fetch('script');
?>
</head>
....
<div id="leftcolumn">
<?php  echo $this->element('sidebar/menu'); ?>
</div>

Elements/sidebar/menu.ctp

$this->Html->script('menu', array('inline' => false));
$this->Html->css('menu', null, array('inline' => false));
<div class="sidebarmenu"><ul><li>Menu Item</li></ul></div>

CSS and javascript are in webroot/css/menu.css and webroot/js/menu.js respectively.

If I put the Html->script and Html->css declarations in a view file or home.ctp or default.ctp they get added to the css and script blocks and are output just fine. When they are declared in the element file menu.ctp they don't work. Is there something I'm missing?

2 Answers 2

2
// css
$this->start('css');
echo $this->Html->css('additionalstyle');
echo $this->Html->css('anotherstyle');
echo $this->end()

// javascript
$this->start('script')
echo $this->Html->script('jquery');
$this->end()

Add this code in your view.ctp

http://book.cakephp.org/2.0/en/views.html

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

Comments

1
echo $this->Html->script('menu', array('inline' => false));
echo $this->Html->css('menu', null, array('inline' => false));

I think I got the problems. Main Problem is the order of css and js calling.

echo $this->fetch('css');
echo $this->fetch('script');

This two lines are echoing within head i.e. before calling you element. So there are two possible solutions for this issue:

  1. cut above fetch() from head and append it before end of body tag so that it load scripts and css after all DOM available. i.e.

    ... ... echo $this->fetch('css'); echo $this->fetch('script');

  2. make "inline" => true i.e.

    echo $this->Html->script('myel', array('inline' => true));
    echo $this->Html->css('mycss', null, array('inline' => true));
    

I think this will solve your problems....

1 Comment

Thanks for the suggestion. I've tried adding echo and it doesn't seem to have helped... any other ideas?

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.