开发者

Zend bootstrap, including javascript files for certain pages only

开发者 https://www.devze.com 2023-03-10 07:57 出处:网络
I\'m loading javascript files in the bootstrap as usual, but there\'s a file that I want to have included only if it\'s a page that has a form

I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

->appendFile('http://myurl.com/js/formscript.js');

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

$layout = new Zend_Layout();
$view = $layout->getView();     
$view->formscript = true; 

and this would be in my bootstrap

if ($view->formscript)
开发者_JAVA技巧

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?


To include javascript files in a particular pages alone, add the following code in those pages(I mean view scripts - *.phtml).

<?php

 $this->headScript()->appendFile('http://myurl.com/js/formscript.js');

?>

Similarly, to add CSS files to a particular page, do the following.

<?php
 $this->headLink()->appendStylesheet('http://myurl.com/styles.css');
?>


It is possible, but you do not need your bootstrap. You can just access the variable from your layout:

//form
$view = Zend_Layout::getMvcInstance()->getView();
$view->formscript = TRUE;

//layout
if($this->formscript)
{
  $this->headScript()->appendFile('http://myurl.com/js/formscript.js');
}
echo $this->headScript();

Do not use getView() in your form as it will return the view object for the form, not for your application. This has tripped me up more than a couple of times >.>


Your idea to set a flag - something like $view->hasForm - in your view seems like a pretty reasonable approach. But as others have noted, it shouldn't be the form itself that attempts to set the flag since it doesn't really have access to view object until rendering time.

Instead, wherever you place a form into your view - probably in a controller, perhaps even in a front controller plugin - simply set your flag there.

Then your view script or layout can call $this->headScript()->appendFile() if the flag has been set.


Why not move over appendFile() to your form class (of course if you use Zend_Form), you would be sure that your JS line will be created only in the same time as your form. The place for this line is good in init() as well as in render()

class Your_Form extends Zend_Form {
    public init(){
        $this->getView()->appendFile('http://myurl.com/js/formscript.js');
        [...]
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号