php - How to include assets (JS) into the layout from a controller - CakePHP -
this duplicate, struggling find same question , answer.
i'm little unsure , confused on how assets handled in cake (2). want include js on specific page, not on every page of app, assume need add controller method? can't find how that. close have come jshelper, seems more constructing js using php rather loading assets.
i aware can $this->html->script('script')
, not work in controller, in view.
although not needed right now, useful able pass variables through included javascript. example of may ajax request on 'edit' screen something: $.ajax({ url: "/pages/edit_ajax/<?= $page->id ?>" });
any gladly received.
in order want use blocks (providing in v2.1+).
in layout file no doubt have line $this->fetch('script')
go find script
block , output layout.
next, in view controller action, let's index()
have matching view index.ctp
. in view can append script script
block.
so in view,
<?php $this->append('script'); // want append script block ?> <script> $(function() { alert('hey there, im on page!'); }) </script> <?php $this->end();?>
when visit controller action see output, @ bottom of page, along other javascript.
as you've appended script in view, ever execute when view loaded.
in regard second question, can set variables view in controller, , echo them javascript.
// controller $this->set('jsvar', 'javascriptinblocks'); // view <?php $this->append('script'); // want append script block ?> <script> $(function() { alert('hey there <?php echo $jsvar;?>'); }) </script> <?php $this->end();?>
Comments
Post a Comment