koral
koral

Reputation: 2965

Twig (Symfony2) doesn't see variable in 'extend' block

I define variable in controller and pass it to template but it's not visible in extend block. The important controller code is:

        $response['html'] = $this->renderView(
            'AldenXyzBundle:Profile:edit_ajax.html.twig', array(
                'isXmlHttpRequest' => $request->isXmlHttpRequest(),
            )
        );

and Twig template

{% extends isXmlHttpRequest ? '::base-ajax.html.twig' : '::base.html.twig' %}

{% block content %}
...
{% endblock %}

and I have exception Variable "isXmlHttpRequest" does not exist in ... while the template

{% extends '::base-ajax.html.twig' %}

{% block content %}
{{ dump(isXmlHttpRequest) }}
...
{% endblock %}

works well and display correct $isXmlHttpRequest value.

I also tried directly in template:

{% extends app.request.isXmlHttpRequest ? '::base-ajax.html.twig' : '::base.html.twig' %}

but I got an exception saying app is undefined.

I'm using symfony v2.0.15 and twig v1.8.2

Upvotes: 2

Views: 3580

Answers (2)

Linkmichiel
Linkmichiel

Reputation: 2130

I was facing the same problem like koral, although the solution given by Besnik for a conditional statement did not work for me. It took me a while to figure out that the reason for this was that I used a combination of a conditional extend {% extend ? : %} plus a form theme {% form_theme form _self %}.

So, after implementing the solution given, I still recieved an exception saying the var app (or in my case the var vars) is undefined. But, for anyone who is facing the same problem: there is a solution:

Create a Twig function, In which you can add all your logic and logistics, and use it in your Twig template:

{% extends parent_template() %}

There is an excelent post regarding this issue. Also see this post in the symfony forum which mentions the issue.

Upvotes: 1

Besnik
Besnik

Reputation: 6529

This will work:

{% set layout = app.request.isXmlHttpRequest ? '::base-ajax.html.twig' : '::base.html.twig' %}
{% extends layout %}

Upvotes: 0

Related Questions