0
votes

I use symfony2 and TWIG, I want to use some global variables to point to the index of tablet in page:

app/config/parameters.ini

tab_branch="1"

app/config/config.yml

twig:
    globals:
        tab_branch: %tab_branch%

src/ACME/BranchBundle/Controller/defaultController.php

/**
 * @Template()
 */
public function showAction($id) {
    ...
    return array(
        'tab' => 'tab_branch',
    );
}

src/ACME/BranchBundle/Resources/views/default/show.html.twig

<input type="hidden" id="tablndex" value="{{ {{ tab }} }}" />  //not working

I really want to do is to make {{ tab }} to be resolved to tab_branch, then {{ tab_branch }} to be resolved to 1 (just like $$foo in PHP), How should I do?

3
Sorry, but this just reeks of bad code smell. Maintaining this will be a nightmare. Could you maybe elaborate a bit more on what exactly is the problem you are trying to solve? - kgilden
Thank you for your advice. What I really want to do was just to mark the current tab. Now I use querystring to pass the tabindex between pages, i.e. abc.com/branch?idx=1, but I really want to discard the querystring, could you suggest other workaround? - Travis Yang
Depending on the complexity of the site you could either check the current route in the template ({{ app.request.attributes.get('_route') == 'FooBar' ? 'foo' : 'bar' }}) or opt for something more complicated, such as writing a custom twig extension or using KnpMenuBundle. - kgilden

3 Answers

0
votes

This cannot be done the way you are trying to do it, twig does not work that way. If there are not many possible values for tab, you could do something like:

{% if tab == 'tab_branch' %}
    {{tab_branch}}
{% else if tab == 'other_tab' %}
    {{other_tab}}
{% endif %}

I know, not very elegant...

0
votes

Write a custom function to allow such evaluation.

You may be interested in this proposal eval function

0
votes

I refer to variables in other variables anywhere within my data with twig syntax:

foo: "{{ bar.baz }}/quu.txt"
bar:
    baz: /tmp

Then I render until the result does not change anymore:

    while( $template !== ($result = $twig->render($template, $data)) )
    {
        $template = $result;
    }

This is

  • inelegant: each variable value should be rendered before embedding it
  • insufficient: variable names are not rendered before use, so foo.{{i}} won't work
  • simple: I don't have to refer to filters or code, just variables.
  • small: implementation above is short and hopefully clear. Could be one-line recursive method as well.