user3139853 user3139853 - 3 years ago 433
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=""></script>
$('#layout').load("{{ asset('layout/myLayout.html.twig') }}", function(){
{% endblock %}


<!-- 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 Source

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.yml
    path: /layout #or whatever you choose
    defaults: { _controller : MyBundle:Layout:index }


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


$('#layout').load("{{ url('layout_route') }}", function(){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download