CakePHP how to addScript() from inside element? - php

I have a navigation menu inside a CakePHP element file (views/elements/nav_default.ctp).
The file is included inside another element that is the header (views/elements/header_default.ctp) which is then included in the layout file (views/layouts/default.ctp).
I am trying to tell Cake to load a js file (webroot/js/mega_drop.js) from within the nav element like so:
<?php
$this->addScript('mega_drop');
?>
It does not get included. I looked at the documentation for addScript which just says:
Adds content to the internal scripts
buffer. This buffer is made available
in the layout as $scripts_for_layout.
This method is helpful when creating
helpers that need to add javascript or
css directly to the layout. Keep in
mind that scripts added from the
layout, or elements in the layout will
not be added to $scripts_for_layout.
This method is most often used from
inside helpers, like the Javascript
and Html Helpers.
The key part:
Keep in mind that scripts added from the layout, or elements in the layout will not be added to $scripts_for_layout.
So how do I do it then?
I guess I could add a <script src="/js/mega_drop.js"></script> to the default.ctp layout. That doesn't feel right though as it would tightly tie the layout and the element together.
Whats the CakePHP best practice way to do this?

addScript() does not load a file; it adds actual code to the $scripts_for_layout variable. The idea being that the layout is a good, common place to load your JavaScript files and code. That way you can output all the code in one location - in the head block or at the end - either way it's together. So if you are in a situation where you've got JavaScript code in the view, rather than output it inline, you can pass it up to the layout.
The best way to load a script file is with the HTML Helper- echo $this->Html->script("script or array('of', 'scripts')"); With that in mind, you could $this->set('scripts', 'mega_drop'); in the element and then call the Html Helper with that $scripts variable from the layout.
The problem with that: it won't work if your nav_default.ctp is called from the layout. $this->set() works inside of a view (or an element called from a view) because the View is rendered before the Layout. If you are calling your element from the layout, then it is too late to be setting viewVars for use in the layout. The best thing to do is set() the scripts variable from the Controller and use a if(isset($scripts)) { echo $this->Html->script($scripts); } in the layout.

Correct and valid 1.3.x CakePHP 2.0 Dev is from example.ctp file:
$this->addScript($this->Javascript->link('tab_enabler'));
$this->addScript($this->Html->css('jquery.tabs'));
This is an example of how to properly include CSS and JS files from the view and adding in the variable $scripts_for_layout to not generate validation error with the W3C as it is not correct to add the link to a css file in <BODY></BODY>

try
$this->Html->script('mega_drop', $inline=false);
in your element without the echo.
The Second parameter says to add it to the $scripts_for_layout variable.
You should be able to do this in your element, so that the javascript is only included when the element is.

Related

Yii add another $content to template

I have Yii template that structure is:
Include CSS files in
echo $content right after
Include Javascript files (like JQPlot) after $content
What I would like to do is add custom mix of Javascript/PHP code after including all Javascript files. I know this can be done just adding the code to the template.
But I have many pages with custom JS/PHP code and I would like to include only the specific code for that page to avoid long load times.
Can I create new element that works like $content, but it would include for example "js.php" from the same View folder as "index.php"? The "js.php" would be in every view folder I need custom code and contain the js/php mix of code for that specific page.
Thanks for the help!
Clips are your best bet, as #jfrej suggests by pointing you to a forum topic where clips are discussed.
Under conventional circumstances, every controller has associated a folder where all its views are placed, and it is the case that you want to include at the end of the layout (this is how they are refered, rather than templates) some PHP+Javascript content that is common to all the actions in the controller.
I would override CController::afterRender() method to capture the content for you clip; lets call your clip controller_content:
afterRender(string $view, string &$output)
$this->beginClip('controller_content');
// output here any content you want to capture into your clip
// e.g. renderPartial, echo, etc.
...
$this->endClip();
parent::afterRender($view, $output);
}
Then, in your layout, you would render your clip after all the stuff that is always there, e.g.:
// register your CSSs
// output $content variable
// register Javascript
...
<?= $this->clips['controller_content'] ?>
Of course, there are various ways for you to generate your clip content. Here I overrode the CController::afterRender() method, but you could also use filters, behaviors or any other approach that best suits your needs.
You can try :
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
You can call it from controller

how to add stylesheet to my layout and pass values from view to layout

I am using zend framework.
My structure is (only included files and folders needed for this question):
application
>configs
>controllers
>forms
>images
>layouts
>scripts
>layout.phtml
>models
>styles
>style.css
>views
>scripts
>index
>index.phtml
Bootstrap.php
docs
library
logs
public
test
I have got the layout working properly. However, I want to ask a couple of questions in order to get my set up perfect for the way I want it.
Is application>styles a good place for the stylesheet to be? If not what's the recommended?
How do i add the stylesheet to the layout?
In my layout I have a title tag : <title>Text</title>. How do I pass values from my controllers to it?
Stylesheets need to be accessible from the browser, so typically you will put these somewhere in the public directory, such as public/css
There are several ways, including placing rel tags in your view/layout, but my preferred option is to use the viewHelper within your controller:
$this->view->headLink()->setStylesheet('/css/style.css');
Then your call to headLink() in the layout file will automatically include the stylesheet.
The way I have done this is to use the Zend_Registry in the past. There may be better ways.

Cakephp splitting long view.ctp into smaller ones

One of my view file in cake is getting very long, like 300+ lines already. And i find it very difficult to keep track of the understanding.
Is it a good idea to split them up into smaller files and then including them in the parent view file?
If its ok to be done,
In what extension should i create the smaller files? .ctp or .php?
Including them with require_once(view-child1.ext) should be fine, right?
Im fairly new to cakePHP. So i prefer advises from the experts over here. Please put me in the right direction.
EDIT
Thanks for the help guys.
I tried it. But i cant seem to pass the variable. echo $this->Element('reviews/view-goal',$history); Parent view shows and error saying undefined variable in that element.
Im calling the elements from this loop:
foreach($histories as $date => $history)
Cant pass $history. But $histories is being passed correctly.
You should make elements in View/Elements folder with .ctp extension.
This link would help you to make clean separation of your view files with the related/repeated code.
An element is basically a mini-view that can be included in other views, in layouts, and even within other elements. Elements can be used to make a view more readable, placing the rendering of repeating elements in its own file. They can also help you re-use content fragments in your application.
Elements live in the /app/View/Elements/ folder, and have the .ctp filename extension. They are output using the element method of the view:
<?php echo $this->element('helpbox'); //without extension ?>
You can pass variables from your view to the element.
In your view:
<?php echo $this->Element('reviews/view-goal', array('history' => $history));
In view-goal.ctp element you can directly access $history variable.
Yes, it is a very good idea. But don't use the normal require() of PHP.
CakePHP has a feature called "elements", a mechanism to put parts of a view into separate .ctp files. The files go in a special folder, View/Elements
You can include an element like this:
echo $this->element('sidebar/recent_comments');
If you need any variables inside the element, you need to pass them in an additional array parameter:
echo $this->element('sidebar/recent_comments', array('variable_name' => /* Variable content */));
In order to keep your view files small, you should also make sure that you put stuff that is shared by most pages (header, footer) into the Layout file. And obviously: keep JS and CSS in external files.

Cakephp, dynamically write variables into css file upon load of view?

I'm working out a process to save actions that occur from jquery in my view in cakephp.. I figure an easy way to load the saved values, such as the width and height for a DIV, would be to have cakephp echo a variable as their width / height in the css file, much the same way it would do this in the view file.. I guess I'm not sure exactly where to look for info on this, if its in the cakephp cookbook I guess I'm missing it as I don't see how to do it in there.. any advice is appreciated.
This is actually pretty easy (and powerful), and can be done without the aid of CakePHP.
First, make a new file in your webroot called css.php. At the top of that file put the following:
<?php header("Content-Type: text/css"); ?>
Now, link to this file in the head of your layout, just as you would a normal CSS file.
<link rel="stylesheet" href="/path/css.php" type="text/css" />
And there you have it, a dynamic CSS file. You can pass information to it like so:
<link rel="stylesheet" href="/path/css.php?c=red&fw=700" type="text/css" />
CLARIFICATION: To access the variables mentioned above, you would use the $_GET variable in the CSS file. Take a look at the link tag above. To access those variables in the css file, you would do something like this:
.class {color:<?php echo $_GET['c']; ?>;font-weight:<?php echo $_GET['fw']; ?>;}
UPDATE: After viewing the link you posted about the CakePHP HTML Helper, I realized that there is a better way to do this if you intend to pass a lot of variables to the css file.
Create a new model and controller called DynamicStyle and DynamicStylesController (or something similar). Then, make a new layout file called css.ctp that all of this controller's views will use. Declare the content-type header statement in that layout file.
The last step would be to link to a method in that controller from the head of your standard layout header.
Now you could make a database table of css rules and use those with the HTML helper in the css view.
I just realized CakePHP has something for this as well:
http://book.cakephp.org/view/1440/style
So this may come in handy for anyone who comes across this in the future

Javascript source in partial view of symfony

I'm using symfony 1.4, I wrote a piece of js code to use in a template, and I want to put it in a JS separated file because I'll use it many times in the code.
I added the JS to the template using:
<?php use_javascript('mi_js') ?>
This templates has some ajax calls that refresh zones of the view with renderPartial method. This new zones also use the JS code, so I need to add this code in the partial view.
But if add:
<?php use_javascript('mi_js') ?>
in the partial, then it doesn't work.
To get this work I have to put all the JS code in the partial, like:
<script type="text/javascript">/*<![CDATA[*/
$('.mi_class').click(function() {
var a = $(this).parent();
...
As I told I don't want to do this.
Any idea what can I do? Any template method to do this?
Thanks in advance.
Alejandro G.
The reason why you have to put the code in the partial is the following:
When you use use_javascript('mi_js') then the (path to the) JS file gets added to the sfResponse object. Then, when the templates get rendered, all the JS files get included into the layout file via get_javascripts().
But now as you only render the partial and send the results back via Ajax, the JS files get not included.
I suggest to put your code into a function and add it to the header of your HTML file. Then in the partials you call:
<script type="text/javascript">/*<![CDATA[*/
$('.mi_class').click(the_new_function())
(Maybe you have to define parameters, I don't know).
You can attach event handlers to future DOM elements via jQuery's live() method. Another way is to bind handlers directly after loading your partial.
How about adding the JS file in a normal way to the parent page that utilises the partial, instead of the partial itself.
If the partial is called in lots of places, I'd just add it to the application's or modules' view.yml file.

Categories