2
votes

I have try to converted my php code to Twig code.

Php code:

<?php foreach ($languages as $language) { 
    if(empty($my_title[$language["language_id"]])){$my_title[$language["language_id"]] ="MY Title";}
?>

to Twig:

{% for language in languages %}
    {% if not my_title[language.language_id] %}
      {% set my_title[language.language_id] = "MY Title" %}
    {% endif %}
{% endfor %}

but, Does get following error.

Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unexpected token "punctuation" of value "[" ("end of statement block" expected) in....

what do wrong here? how to write properly this code in twig?

1

1 Answers

5
votes

You cannot add items to arrays or hashes in Twig directly. You need to use merge filter, like this:

{% set my_title = my_title|merge({(language.language_id): 'MY Title'}) %}

Notice the parenthesis around language.language_id. That's because a hash key cannot be an expression but a literal. Parenthesis around language.language_id make sure that the expression is evaluated before being used as the hash key.

In addition, your if statement will fail if my_title hash does not have the key stored in language.language_id variable. You should use is defined test there.

Complete example:

{% for language in languages %}
    {% if not my_title[language.language_id] %}
        {% set my_title = my_title|merge({(language.language_id): 'MY Title'}) %}
    {% endif %}
{% endfor %}