Twig在for循环中添加了空格

I'm adding a function to an existing project, so i have to use twig. I'm displaying translations of a word, so i have a list of objects. The object has multiple attributes.

 {% for trans in Translations.dictionaryList[0].wordTranslationsList|sortLangAndFreqClass %}
        {% if currentLanguage is not same as (trans.targetLanguage) %}
            {% set currentLanguage = trans.targetLanguage %}
            {% set first = TRUE %}<b> {{- Languages[(currentLanguage |upper)] -}}: </b>
        {% endif %}
        {% if not first %}, {% endif %}
            <a href="{{'res'|url({'view_language' : view_language, 'corpusId': trans.corpus, 'word' : trans.translation})}}">{{- trans.translation -}}</a> ({{- trans.freqClass -}})
        {% set first = FALSE %}
    {% endfor %}

The output is like: Danish: hus (10) English: home (6) , business (7) , family (7) , live (8) , house (8)

But I want to remove white spaces before the comma, so it should be:

Danish: hus (10) English: home (6), business (7), family (7), live (8), house (8)

I found the solution to write everything in one line, but this is very ugly and not possible to read. Is there any other way to solve this?

I believe this isn't a twig issue, but rather just how html works. In regular html, if you have a newline before any character, it will be converted to a regular space.

<p>something
,
another thing</p>

will be displayed as

something , another thing

Now, looking at the twig docs[1], I've found that there's an implicit variable loop inside any loop (like the for you're using). Two attributes of this variable are loop.first and loop.last, that tells you if the current element is either the first or the last element.

You could, instead of using the first approach, use the last element and have something like this

{% for trans in Translations.dictionaryList[0].wordTranslationsList|sortLangAndFreqClass %}
        {% if currentLanguage is not same as (trans.targetLanguage) %}
            {% set currentLanguage = trans.targetLanguage %}
            <b> {{- Languages[(currentLanguage |upper)] -}}: </b>
        {% endif %}

        <a href="{{'res'|url({'view_language' : view_language, 'corpusId': trans.corpus, 'word' : trans.translation})}}">{{- trans.translation -}}</a> ({{- trans.freqClass -}}){% if not loop.last %}, {% endif %}
    {% endfor %}

Notice how I've appended the {% if not loop.last %}, {% endif %} at the <a> tag line.

I can't guarantee it will work as I don't have how to try it here, but give it a shot.

[1] - https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

You can one-line it like this:

{% set items = [ 'foo', 'bar', 'foobar', 'barfoo', ] %}
{% for item in items %}
    {{- ((not loop.first ? ', ')~'<a href="http://www.example.com#'~item~'">'~item~'</a>') | raw -}}
{% endfor %}

demo