QGIS Labeling – How to Avoid Empty Lines in QGIS Labels

expressionfields-attributeslabelingqgisstring

I´m new to QGIS yet very exited of the learning curve and automatisms it provides.
But at some point i dont manage to work around a problem.
I want to label a vector layer with differnt attributes in a netdocumantation.
I have 7 attributes for different types of cables, the attribute type is boolean, so that i just have to checkbox which cables are inside the trench.
When i label the trench now, i get empty lines where the cables arent checkboxed. How could i get rid of these?

enter image description here

Best Answer

The advantage of this solution is that it works automatically, without any manual intervention: you can use the expression without any change regardless how your fields are named and how many fields you add (or delete or rename).

So to automatize the process and avoid the need to manually repeat the expression for every single attribute field, you can use the functions attributes() and map_akeys() to get a list of all fieldnames.

Then check which of these fields contain the value true and return the names of of these fields only. Use this expression that will output a list with each fieldname in a separate row, avoiding any empty rows:

array_to_string (
    array_filter (
        array_foreach(
            map_akeys(attributes()),
            if (
                attribute (
                    get_feature_by_id (@layer, $id),
                    @element
                )='true',
                @element,
                ''
            )
        ), 
        @element <>''
    ),
    delimiter:='\n'
)

The expression, used here as source of a dynamic label. It takes into consideration only those fields that contain as value the text string true and in this case returns the fieldname, with each name on a separate row, but without any empty rows:

enter image description here

Related Question