Symfony 1.4 and pjax (ajax pushstate)?
symfony: http://www.symfony-project.org pjax: https://github.com/defunkt/jquery-pjax
Hi all,
I'm trying to use pjax in symfony in order to speed up our website (we will be able to keep header and footer static most of the time, and also avoid reloading lots of css/js and other files).
I have no problem with ajax or symfony, but I want to know if there is a better way:
- Is it a good idea to use postExecute to return the html code back right away without sf going to the template at all
If so, can I somehow write this only once for all modules? I imagine that I can do:
mySfActions extends sfActions
moduleActions extends mySfActions
I wonder if there is a better way? 3. Is ther开发者_如何学Goe a way to get the current layout name (defined in the module's view.yml) within the controller/action?
Question 1: Don't use post-execute like that. If you need to return html from an ajax call in your action then your action should return like this:
return $this->renderText("<p>Your html result.</p>");
This will skip the template call.
Question 2: That is correct. You have written the best way to write a function once and have it available to all module actions.
There is nothing to do.
When calling an action via XmlHttpRequest, symfony automaticaly skip the Layout render, and only return the module render.
You need to put all your "static" assets and html in your layout and that's all.
Thank you all for helping me, all your answers were helpful and pointed me to the right direction. I wanted to vote for both answers but since I can only accept one, I accepted the very first answer.
Anyhow, here is what I did:
First, I extended the sfActions class so I don't have to do add preExecute on every module:
<?php
class mySfActions extends sfActions{
public function preExecute(){
$request = $this->getRequest();
if ($request->getParameter('_pjax')) {
$this->setLayout(false);
}
}
}
Then of course each of my module action class must extend this new class.
Inside my individual template I have something like this:
<?php if($sf_request->getParameter('_pjax')):?>
<script type="text/javascript" src="/js/question_list.js"></script>
<?php endif;?>
This currently seems to work quite well for me, I'm enjoy the incredible loading speed when pushstate is supported, and still able to fallback when it is not (on the dumb IE for example)
精彩评论