Reputation: 122
I'm not sure if my title is accurate, so I'll do my best to explain here.
What I'm trying to attempt to do is to call my controller with Ajax and have it change the content on the page without reloading (The content being defined by blocks). So for a loose example, on arrival of the homepage, the homepage's content would be:
# routing.yml
StackQuestionBundle_osgs_home:
pattern: /
defaults: { _controller: StackQuestionBundle:Pages:index }
options:
expose: true
StackQuestionBundle_osgs_page:
pattern: /page
defaults: { _controller: StackQuestionBundle:Pages:page }
options:
expose: true
<!-- @StackQuestionBundle:Pages:index.html.twig -->
<header>
{% block title %} <!-- Title --> {% endblock %}
<nav> </nav>
</header>
<main>
<aside> <!-- Sidebar --> </aside>
<section>
{% block content %} <!-- Main Content -->{% endblock %}
</section>
</main>
<footer>
{% block footer %} <!-- content --> {% endblock %}
<nav> </nav>
</footer>
// JS
$('nav button.test').click(function() {
$.ajax({
url: "{{ path('OSGSBundle_osgs_page') }}",
type: "POST",
success: function(data) {
//Change the content in the blocks!
//alert("It worked!")
}
});
});
# PagesController.php
namespace MyNameSpace\StackQuestionBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class PagesController extends Controller
{
public function indexAction()
{
return $this->render('OSGSBundle:Pages:index.html.twig');
}
public function pageAction(Request $request)
{
$isAjax = $this->get('Request')->isXMLHttpRequest();
if ($isAjax)
{
// Replace/Append the content in index.html.twig with the content from page.html.twig
}
else
{
// Load page normally if navigated to http://localhost/page
return $this->render('OSGSBundle:Pages:page.html.twig');
}
}
}
This is what my current code looks like. So far, I've managed to replace data according to DOM elements only. So, I'd replace all the information in my <main>
tag for instance. I ONLY want to replace content in my Twig block tags. Side note: I'm using FOSJSRoutingBundle to change the URLs.
Thanks in advance, I appreciate the help/advice. I hope this wasn't too confusing.
Upvotes: 2
Views: 4714
Reputation: 5986
I guess there is no generic way of changing twig blocks via javascript, because javascript is clientside and twig is serverside.
You have to do it manually by wrapping the block in a div or whatever tag with an id.
<section id="block-content">
{% block content %} <!-- Main Content -->{% endblock %}
</section>
Then you can apply normal ajax behaviour and render a ajax template on the server for the response, as toine pointed out and change content in the element with the id.
Upvotes: 1
Reputation: 450
1) Add a new twig file for your block : myblock.html.twig
2) Update your controller
if ($isAjax)
{
return $this->render('OSGSBundle:Pages:myblock.html.twig');
}
Upvotes: 1