简体   繁体   中英

Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unexpected token “punctuation”

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?

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM