0

In my symfony project, I pass from the Controller a variable called 'button'.

In this case 'button' has the value 'content' but this is not always.

I need it to display the content of phrase.content in the '.html.twig' file but I can't.

index.html.twig:

button = 'content'

{% for frase in frases %}

    <tr>
        <th scope="row">{{ frase.id }}</th>
        <td>{{ frase. ~ button }}</td>
    </tr>

{% endfor %}

I have tried like this but it gives me the following error:

Expected name or number. (500 Internal Server Error)

----EDIT----

If I put frase.content directly it does, but if I put frase[button], it gives an error

Impossible to access a key" content"on an object of class" App \ Entity \ Frase"
that does not implement ArrayAccess interface.
1
  • frase[button]. done. Commented May 29, 2020 at 23:15

2 Answers 2

2

I believe this twig's check could solve your problem:

{% if foo.bar is defined %}

See doc: https://twig.symfony.com/doc/2.x/tests/defined.html

Also If you want to access object's property you can use twig function

attribute

Link https://twig.symfony.com/doc/2.x/functions/attribute.html

So in your case it would be something like:

{{ attribute(frase, button) ?? '' }}

Also you can additionally check if 'button' variable is defined

Sign up to request clarification or add additional context in comments.

Comments

0

frase. expects something after the dot. A dot like this in twig is kind of like 's: In the table header you ask for frase's id. In the table definition (td) element, twig essentially thinks:

frase's " ~ button"?? I was expecting a property!

If button contains the name of the property you wish to show, you can use:

frase[button]

In that case, if button is "content", twig will read it as

frase's content

PS: did you mean {% for phrase in phrases %}?

1 Comment

If I put frase.content directly it does, but if I put frase[button], it gives an error Impossible to access a key" content"on an object of class" App \ Entity \ Frase"that does not implement ArrayAccess interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.