user3139853 user3139853 - 2 months ago 42
Twig Question

Using twig variable inside load jQuery

I have a problem with including twig inside load function of jQuery, here is an example:

<!-- src/MyBundle/Ressources/views/index.html.twig -->

{% extends'base.html.twig' %}
{% block body %}
<div id="layout"></div>

{% endblock %}
{% block javascripts %}
<script src="https://code.jquery.com/jquery-2.2.0.js"></script>
<script>
$(function(){
$('#layout').load("{{ asset('layout/myLayout.html.twig') }}", function(){
alert($('#link').attr('href'));
});
})
</script>
{% endblock %}


and

<!-- web/layout/myLayout.html.twig -->
<a id="link" href="{{ asset('layout/myLayout.html.twig') }}"> link </a>


In this example when I load the page, Alert display {{ asset('layout/myLayout.html.twig') }} instead of http://localhost/myProject/web/layout/myLayout.html.twig

It is not interpreted as a twig variable, but as the text

Thank's for your help

Answer

This is because you're just loading the twig template file with your ajax load method, so the contents of that file are not being interpreted. You need to create a route and a controller to render the file 'layout/myLayout.html.twig' and use that in your load method.

For instance if you create a route called layout_route and that defines a controller action that renders your layout/myLayout.html.twig template:

Routing:

# routing.yml
layout_route:
    path: /layout #or whatever you choose
    defaults: { _controller : MyBundle:Layout:index }

Controller:

// MyBundle/Controller/LayoutController
public function indexAction()
{
    return $this->render('MyBundle::myLayout.html.twig', array();
}

Javascript:

$('#layout').load("{{ url('layout_route') }}", function(){
    alert($('#link').attr('href'));
});